我对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);
该构造函数创建的新实例国防部正确地使用应用功能,但它的原型是不是原。我缺少什么来阻止mod成为原型时使用proto构建?
这是上面的代码的小提琴。
谢谢堆!
.prototype
分配对您不起作用的原因是,像这样设置原型链仅在您new
对构造函数使用运算符时才有效。
您创建了一个工厂函数,该函数返回一个新创建的对象。创建实例时,请摆脱return
inmod
并使用它this
来附加您的方法和usenew
运算符,mod
以使.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);
编辑:通过传递与应用的args添加。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句