次のコードは、MDN ページの から取得したものですFunction.prototype.apply
。
Function.prototype.construct = function (aArgs) {
var fConstructor = this,
fNewConstr = function () { fConstructor.apply(this, aArgs); };
fNewConstr.prototype = fConstructor.prototype;
return new fNewConstr();
};
function MyConstructor() {
for (var nProp = 0; nProp < arguments.length; nProp++) {
this["property" + nProp] = arguments[nProp];
}
}
var myArray = [4, "Hello world!", false];
var myInstance = MyConstructor.construct(myArray);
alert(myInstance.property1); // alerts "Hello world!"
alert(myInstance instanceof MyConstructor); // alerts "true"
alert(myInstance.constructor); // alerts "MyConstructor"
このコードについて 2 つの質問があります。
var myInstance = new MyConstructor();
使用すると が呼び出されることはわかってMyConstructor()
いますが、どのようにvar myInstance = MyConstructor.construct(myArray);
呼び出すのMyConstructor()
ですか?MyConstructor.construct(myArray);
のメソッドとして呼び出されましたが、そのメソッドはではなくMyConstructor
として宣言されました。とはどう違いますか?Function.prototype.construct
MyConstructor.prototype.construct
Function.prototype.construct
MyConstructor.prototype.construct