我正在尝试以这种方式使用模块模式实现继承:
Parent = function () {
//constructor
(function construct () {
console.log("Parent");
})();
// public functions
return this.prototype = {
test: function () {
console.log("test parent");
},
test2: function () {
console.log("test2 parent");
}
};
};
Child = function () {
// constructor
(function () {
console.log("Child");
Parent.call(this, arguments);
this.prototype = Object.create(Parent.prototype);
})();
// public functions
return this.prototype = {
test: function()
{
console.log("test Child");
}
}
};
但我无法从子实例调用 test2()
。
var c = new Child();
c.test2(); // c.test2 is not a function
我错了什么?
最佳答案
您没有以正确的方式使用模块模式。不知何故,您的“构造函数”被称为立即调用的函数表达式( IIFE ),而模块闭包则不是。应该反过来。
此外,您不能分配给 this.prototype
。要创建所有实例都将继承的原型(prototype)对象,您需要分配给 构造函数 的 prototype
属性(this
keyword 甚至指向全局 window
对象在你的情况下)。
而且你应该从 IIFE 中返回构造函数,而不是原型(prototype)对象。
Parent = (function () {
// constructor
function construct () {
console.log("Parent");
};
// public functions
construct.prototype.test = function () {
console.log("test parent");
};
construct.prototype.test2 = function () {
console.log("test2 parent");
};
return construct;
})();
Child = (function () {
// constructor
function construct() {
console.log("Child");
Parent.apply(this, arguments);
}
// make the prototype object inherit from the Parent's one
construct.prototype = Object.create(Parent.prototype);
// public functions
construct.prototype.test = function() {
console.log("test Child");
};
return construct;
})();
关于javascript - 继承和模块模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15436533/