除了eval之外,还有其他方法可以使用变量参数列表来实例化对象吗?
例如: var foo = instantiate(className, [arg1, arg2, ...])
Dav*_*ang 19
您可以使用可变参数列表实例化对象,如下所示:
function instantiate(className, args) {
var o, f, c;
c = window[className]; // get reference to class constructor function
f = function(){}; // dummy function
f.prototype = c.prototype; // reference same prototype
o = new f(); // instantiate dummy function to copy prototype properties
c.apply(o, args); // call class constructor, supplying new object as context
o.constructor = c; // assign correct constructor (not f)
return o;
}
Run Code Online (Sandbox Code Playgroud)
附注:您可能希望直接引用类构造函数:
var foo = instantiate(Array, [arg1, arg2, ...]);
// Instead of:
var foo = instantiate("Array", [arg1, arg2, ...]);
Run Code Online (Sandbox Code Playgroud)
...这使得它与非全局函数兼容.
在ES5中使用Object.create():
function instantiate(constructor, args) {
var instance = Object.create(constructor.prototype);
constructor.apply(instance, args);
return instance;
}
Run Code Online (Sandbox Code Playgroud)
在ES6中使用扩展运算符:
var foo = new constructor(...args);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4506 次 |
| 最近记录: |