[英]Construct an object with a prototype using Function.apply()
我对JS的原型继承有个困惑。 我想做的是:
定义一个名为mod的对象
var mod = function() { function sayGoodbye() { alert("Goodbye!"); } function saySomethingElse(message) { alert(message); } return { sayGoodbye: sayGoodbye, saySomethingElse: saySomethingElse }; };
定义一个称为proto的原型对象
var proto = { sayHello: function() { alert("Hello!"); } };
将mod的原型设置为proto
mod.prototype = proto;
调用一个函数,该函数使用proto原型构造mod的新实例
function construct(constructor, args) { function constructorWrapper() { return constructor.apply(this, args) } constructorWrapper.prototype = constructor.prototype; return new constructorWrapper(); } var foo = construct(mod, ["Other Message 1"]); var bar = construct(mod, ["Other Message 2"]); console.dir(foo); console.dir(bar);
构造函数使用apply函数正确创建了mod的新实例,但是它的原型不是proto 。 我缺少的是防止国防部从原正在建造之中,它的原型?
这是上面代码的小提琴 。
谢谢堆!
.prototype
分配对您.prototype
的原因是,像这样设置原型链仅在对构造函数使用new
运算符时才有效。
您创建了一个工厂函数,该函数返回一个新创建的对象。 摆脱mod
中的return
,并使用this
来附加您的方法,并在创建mod
实例时使用new
运算符使.prototype
分配起作用。
这可能令人困惑,所以我更新了您的小提琴: https : //jsfiddle.net/6fdo649y/1/
有几种方法可以实现您要完成的任务,但是此示例说明了为什么您看不到.prototype
工作。
//Constructor function using this
function Mod(arg1) {
this.sayGoodbye = function sayGoodbye() {
alert("Goodbye!");
}
this.saySomethingElse = function saySomethingElse(message) {
alert(message);
}
this.arg1 = arg1;
};
var proto = {
sayHello: function() {
alert("Hello!");
}
};
Mod.prototype = proto;
function construct(constructor, args) {
function constructorWrapper() {
constructor.apply(this, args)
}
constructorWrapper.prototype = constructor.prototype;
return new constructorWrapper();
}
var foo = construct(Mod, ["Other Message 1"]);
var bar = construct(Mod, ["Other Message 2"]);
console.dir(foo === bar);
console.dir(foo);
console.dir(bar);
编辑:通过传递与应用的参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.