lau*_*kok 1 javascript prototype prototypal-inheritance
如何扩展原型并向其中添加新方法?例如,我想将Shape(超类)扩展为一个子类Rectangle。我扩展它是因为我想在Shape中使用方法,但是在Rectangle中添加更多方法(并覆盖一些Shape的方法)。
但是在Rectangle中添加方法后,我无法再使用/访问Shape中的方法,
// Shape - superclass
function Shape() {
this.x = 0;
this.y = 0;
}
// superclass method
Shape.prototype.move = function(x, y) {
this.x += x;
this.y += y;
console.info('Shape moved.');
};
// Rectangle - subclass
function Rectangle() {
Shape.call(this); // call super constructor.
}
// subclass extends superclass
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
Rectangle.prototype = {
jump : function(){
return 'Shape jumped';
}
};
var rect = new Rectangle();
console.log('Is rect an instance of Rectangle? ' + (rect instanceof Rectangle)); // true
console.log('Is rect an instance of Shape? ' + (rect instanceof Shape)); // true
rect.move(1, 1); // TypeError: rect.move is not a function
Run Code Online (Sandbox Code Playgroud)
我追求的结果
// Outputs, 'Shape moved.'
Run Code Online (Sandbox Code Playgroud)
有什么想法我错过了吗?
您在Rectangle.prototype这里覆盖:
Rectangle.prototype = {
jump : function(){
return 'Shape jumped';
}
};
Run Code Online (Sandbox Code Playgroud)
您应该改为添加:
Rectangle.prototype.jump = function(){
return 'Shape jumped';
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
299 次 |
| 最近记录: |