javascript - OO Javascript 继承向下两级

标签 javascript oop

我继承一个对象如下:

projectile.prototype = Object.create(interactiveElement.prototype);
function projectile(){
    interactiveElement.call(this);
}

interactiveElement 有一个已定义的方法draw。

interactiveElement.prototype.draw = function(){

}

当我这样调用它时,它工作正常

var myArrow = new projectile();
myArrow.draw();

但是如果再次继承并从中调用draw方法:

arrow.prototype = Object.create(projectile.prototype);
function arrow(){
    projectile.call(this);
}

var myArrow = new arrow();
myArrow.draw();

然后我收到错误“箭头没有‘绘制’方法”。只能继承一次吗?我做得正确吗?

最佳答案

这是一个工作示例 ( http://jsfiddle.net/2n62J/ )

function interactiveElement() {
}

interactiveElement.prototype.draw = function(){
    console.log('draw');
};

function projectile() {
    interactiveElement.call(this);
}

projectile.prototype = Object.create(interactiveElement.prototype);
projectile.prototype.fire = function() {
    console.log('projectile fire');
};

function arrow() {
    projectile.call(this);
}
arrow.prototype = Object.create(projectile.prototype);
arrow.prototype.fire = function() {
    projectile.prototype.fire.call(this); // if you want to call the parent function
    console.log('arrow fire');
};

var myArrow = new projectile();
myArrow.draw();
myArrow.fire();

var myArrow2 = new arrow();
myArrow2.draw();
myArrow2.fire();

关于javascript - OO Javascript 继承向下两级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20763413/

相关文章:

php - 如何使用ajax访问返回的php变量,作为 View 中的php变量

java - Java 的面向对象风格编程

C#/面向对象的概念书和代码示例

javascript - 从外部 JS 文件引用 ASPX 控件

javascript - 如何将了解更多链接直接指向选项卡?

javascript - Accordion 折叠时如何隐藏 Accordion 的底部边框?

oop - 确保在方法 B 之前调用方法 A 的设计模式

oop - 清洁架构 - Robert Martin - 用例粒度

python - 按名称引用对象作为属性

javascript - 如何防止响应模式下图像换行