这只是我个人的看法,但我一直觉得 JavaScript 中的原型继承模型很难理解。编写代码时很难推理,6个月后维护代码更难推理。
但是,我认为您要问的实际上只是这样:“我可以编写一个从匿名类继承其成员方法的类吗?” 当你这样改写它时,我认为很明显这种方法存在不确定的价值。编写类的全部目的是支持简单的抽象和封装,同时保持组合紧密。
使用传统对象会更直接,ala:
var main = {
get: {
registration: function() {
//TODO
}
}
}
而且main.get.registration()
很简单。如果您可以利用 Object.create() 和 Object.defineProperties() 来做到这一点,那就更好了。
如果您绝对必须使用原型继承,我喜欢Kistner 先生提出的简单 Function.prototype 扩展:
Function.prototype.inheritsFrom = function(parentClassOrObject) {
if (parentClassOrObject.constructor === Function) {
//Normal Inheritance
this.prototype = new parentClassOrObject;
this.prototype.constructor = this;
this.prototype.parent = parentClassOrObject.prototype;
} else {
//Pure Virtual Inheritance
this.prototype = parentClassOrObject;
this.prototype.constructor = this;
this.prototype.parent = parentClassOrObject;
}
return this;
};
这使您可以像这样组合类和继承:
/***
* Method to create a Class with optional inheritance.
* Generally, I oppose this semantic in JS:
* partly because of the ineffability of the 'this' operator,
* and partly because of the difficulty in grokking this.
* What we're really saying here (through the wonders of functional programming) is this:
*
* var MyClass1 = function(param1) {
* var ret = this;
* ret.id = param1;
* return ret;
* };
*
* var MyClass2 = function(param1, param2) {
* var ret = this;
* MyClass1.apply(this, Array.prototype.slice.call(arguments, 0));
* ret.name = param2;
* return ret;
* };
*
* MyClass2.prototype = new MyClass1;
* MyClass2.prototype.constructor = MyClass1;
* MyClass2.prototype.parent = MyClass1.prototype;
*
* I find this whole mode of operation as dull as it is stupid.
* Nonetheless, there are occasions when the convention is suitable for type/instance checking
*
* Obviously, this method has very little utility if you are not using prototypal inheritance
*/
var MyClassCreatorMethod = function(name, inheritsFrom, callBack) {
var obj = Object.create(null);
obj[name] = function() {
try {
if(inheritsFrom ) {
inheritsFrom.apply(this, Array.prototype.slice.call(arguments, 0));
}
callBack.apply(this, Array.prototype.slice.call(arguments, 0));
} catch(e) {
//do something
}
};
if(inheritsFrom) {
obj[name].inheritsFrom(inheritsFrom);
}
return obj[name];
};
从这里开始,菊花链继承类变得微不足道。我刚刚从我的一个项目中提取了这个,所以并不是所有的语义都适用于你——它只是为了说明一种以更容易理解的方式对行为进行功能化的方法。