Aad*_*hah 6 javascript prototype instantiation
我使用以下函数从一组参数创建JavaScript中的函数实例:
var instantiate = function (instantiate) {
return function (constructor, args, prototype) {
"use strict";
if (prototype) {
var proto = constructor.prototype;
constructor.prototype = prototype;
}
var instance = instantiate(constructor, args);
if (proto) constructor.prototype = proto;
return instance;
};
}(Function.prototype.apply.bind(function () {
var args = Array.prototype.slice.call(arguments);
var constructor = Function.prototype.bind.apply(this, [null].concat(args));
return new constructor;
}));
Run Code Online (Sandbox Code Playgroud)
使用上面的函数,您可以按如下方式创建实例(请参阅小提琴):
var f = instantiate(F, [], G.prototype);
alert(f instanceof F); // false
alert(f instanceof G); // true
f.alert(); // F
function F() {
this.alert = function () {
alert("F");
};
}
function G() {
this.alert = function () {
alert("G");
};
}
Run Code Online (Sandbox Code Playgroud)
上面的代码适用于用户构建的构造函数F.但是,Array由于明显的安全原因,它不适用于本机构造函数.您可能总是创建一个数组,然后更改其__proto__属性,但我在Rhino中使用此代码,因此它不会在那里工作.有没有其他方法可以在JavaScript中实现相同的结果?