javascript 原生原型:扩展、添加和覆盖方法?
javascript native prototype: extend, add and overwrite methods?
如何扩展原型并向其中添加新方法?例如,我想将 Shape(超类)扩展到一个子类 - Rectangle。我扩展它是因为我想使用 Shape 中的方法,但是 添加更多 方法(和 overwrite 一些 Shape 的方法)在 Rectangle.
但是在 Rectangle[= 中添加方法后,我 不能 使用/访问 Shape 中的方法31=],
// 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
我要的结果,
// Outputs, 'Shape moved.'
有什么想法我错过了什么吗?
您在此处覆盖 Rectangle.prototype
:
Rectangle.prototype = {
jump : function(){
return 'Shape jumped';
}
};
您应该改为添加:
Rectangle.prototype.jump = function(){
return 'Shape jumped';
}
如何扩展原型并向其中添加新方法?例如,我想将 Shape(超类)扩展到一个子类 - Rectangle。我扩展它是因为我想使用 Shape 中的方法,但是 添加更多 方法(和 overwrite 一些 Shape 的方法)在 Rectangle.
但是在 Rectangle[= 中添加方法后,我 不能 使用/访问 Shape 中的方法31=],
// 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
我要的结果,
// Outputs, 'Shape moved.'
有什么想法我错过了什么吗?
您在此处覆盖 Rectangle.prototype
:
Rectangle.prototype = {
jump : function(){
return 'Shape jumped';
}
};
您应该改为添加:
Rectangle.prototype.jump = function(){
return 'Shape jumped';
}