更优化的方法几乎就像你正在做的那样,但是你调用父方法this
:
child.prototype.two = function(arg1, arg2) {
parent.prototype.two.call(this, arg1, arg2);
};
但是我建议你使用自定义函数来扩展,你可以使用extend
from jsbase
如果您正在使用 ECMAScript 5 getter/setter(如果不只使用第一个),您可能更喜欢使用这个要点的那个
两者都可以根据 Dean Edward 的想法以相同的方式使用:
var Animal = extend(Object, {
constructor: function(name) {
// Invoke Object's constructor
this.base();
this.name = name;
// Log creation
console.log('New animal named ' + name);
},
// Abstract
makeSound: function() {
console.log(this.name + ' is going to make a sound :)');
},
});
var Dog = Animal.extend({
constructor: function(name) {
// Invoke Animals's constructor
this.base(name);
// Log creation
console.log('Dog instanciation');
},
bark: function() {
console.log('WOF!!!');
},
makeSound: function() {
this.base();
this.bark();
}
});
var pet = new Dog('buddy');
// New animal named buddy
// Dog instanciation
pet.makeSound();
// buddy is going to make a sound :)
// WOF!!!
在您的情况下,它可以是:
var parent = extend(Object, {
one: function() {
$('body').append("Parent: one <br/>");
},
two: function() {
this.one();
$('body').append("Parent: two <br/>");
}
});
var child = parent.extend({
one: function() {
$('body').append('Child: one <br />');
},
two: function() {
$('body').append('Child: do some child stuff here and call parent: <br />');
this.base();
}
});