我决定尝试一下 JavaScript 天才 John Resig 的“简单 JavaScript 继承”,详见此博客页面:
http://ejohn.org/blog/simple-javascript-inheritance/
我很好奇如何使用调用超级方法的代码覆盖方法。换句话说,假设我从一个Person类开始:
var Person = Class.extend({
init: function ( name, age ) {
this.name = name;
this.age = age;
}
});
我扩展该Person类以创建一个新类Worker:
var Worker = Person.extend({
init: function ( name, age, occupation ) {
this.name = name;
this.age = age;
this.occupation = occupation;
}
});
init方法的两个版本中存在重复代码。无论我使用哪个类,都会执行以下两行:
this.name = name;
this.age = age;
看来我应该能够从Hero类的init方法中调用Person类的init方法,然后用占位属性抛出额外的代码行。
不过,我不能用 Resig 先生的代码做到这一点。以下不起作用:
var Worker = Person.extend({
init: function ( name, age, occupation ) {
this._super(arguments);
this.occupation = occupation;
}
});
一旦从Person调用来创建Worker类的extend方法看到 *this._super(arguments)* ,它就会用Person 的init替换整个Worker 的init ,留下一个未定义的占用属性。
有没有人对如何在不必修改 Resig 先生的代码的情况下解决这个问题有任何建议?我目前正在尝试不同的方法来实现“超级”的概念,但我无法让它与现有代码一起工作的事实一直困扰着我。:-)
更新:我意识到我在实现 Resig 先生的代码时犯了一个小错误,这就是我描述的方式的原因。@chuckj 也正确指出了Worker 的 init错误。