javascript原生原型:扩展、添加和覆盖方法
javascript native prototype: extend, add and overwrite methods?
如何扩展原型并向其中添加新方法?例如,我想将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
我追求的结果,
// Outputs, 'Shape moved.'
你知道我错过了什么吗?
您在此处覆盖Rectangle.prototype
:
Rectangle.prototype = {
jump : function(){
return 'Shape jumped';
}
};
您应该添加以下内容:
Rectangle.prototype.jump = function(){
return 'Shape jumped';
}
相关文章:
- 将添加一个相同类型的事件附加或覆盖以前添加的具有相同名称的事件
- javascript函数将数据添加到屏幕,但随后被另一个函数覆盖
- 如何将可调整大小、可拖动的覆盖添加到网页中
- 如何在视频标签中添加按钮覆盖
- 如何在不覆盖的情况下添加同一JPanel类的不同实例
- 将角度控制器添加到因果报应覆盖(伊斯坦布尔)代码覆盖预处理器
- 将覆盖添加到除元素之外的主体
- 在覆盖和关闭按钮或链接中为img添加边框
- 如何覆盖Asp.Net UpdatePanel(动态)添加的Javascript函数
- javascript原生原型:扩展、添加和覆盖方法
- 使用 CSS 覆盖通过 JS 添加的内联样式
- Internet Explorer 在 jQuery 鼠标向下处理程序中添加覆盖层后泄漏单击事件
- 在覆盖层上添加事件侦听器
- 添加事件侦听器而不覆盖
- jQuery:在调整窗口大小时添加和删除元素,但始终覆盖窗口
- 如何覆盖 Backbone.sync,以便在末尾添加 apikey 和用户名
- 我想克隆一个 javascript 类. 将方法添加到克隆的属性中,而不实际覆盖现有方法
- 添加但不覆盖文本
- 高光幻灯片:如何在画廊后面添加覆盖,使所有页面内容变暗
- 悬停在井内时向引导程序缩略图添加覆盖