我喜欢返回构造函数的模块模式,如下所述: http://elegantcode.com/2011/02/15/basic-javascript-part-10-the-module-pattern/
但是我不确定如何从使用此模式实现的对象继承。假设我有一个父对象实现...
namespace('MINE');
MINE.parent = (function() {
// private funcs and vars here
// Public API - constructor
var Parent = function (coords) {
// ...do constructor stuff here
};
// Public API - prototype
Parent.prototype = {
constructor: Parent,
func1: function () { ... },
func2: function () { ... }
}
return Parent;
}());
如何定义一个子对象,该对象也使用继承自parent
的模块模式,以便我可以有选择地覆盖,例如func2
?
答案 0 :(得分:17)
MINE.child = (function () {
var Child = function (coords) {
Parent.call(this, arguments);
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
Child.prototype.func2 = function () { ... };
return Child;
}());
答案 1 :(得分:1)
我发现此博客(http://metaduck.com/08-module-pattern-inheritance.html)的解决方案更清晰。例如:
function Parent(name) {
// Private variables here
var myName;
// Constructor
myName = name;
// Public interface
return {
func1: function () {alert("Parent func1. Name: " + myName); },
func2: function () {alert("Parent func2. Name: " + myName); }
}
}
function Child(name) {
// Private variables here
var myName,
exportObj;
// Constructor
// Inherit
exportObj = Parent(name + "'s father");
// Override
exportObj.func2 = function () {
alert("Child func2. Name: " + name);
}
// Export public interface
return exportObj;
}
可以在此处运行示例:http://jsfiddle.net/wt4wcuLc/