Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/flash/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
OOJavaScript继承向下两级_Javascript_Oop - Fatal编程技术网

OOJavaScript继承向下两级

OOJavaScript继承向下两级,javascript,oop,Javascript,Oop,我正在继承一个对象,如下所示: projectile.prototype = Object.create(interactiveElement.prototype); function projectile(){ interactiveElement.call(this); } interactiveElement有一个已定义的方法draw interactiveElement.prototype.draw = function(){ } 当我这样称呼它时,它工作得很好 var m

我正在继承一个对象,如下所示:

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();
然后我得到错误“arrow没有方法‘draw’”。你只能继承一次吗?我做得对吗?

这是一个有效的例子()


没有时间回答一个大问题,看看这篇文章,如果你有错误,它可能在其他地方,因为你提交的代码是有效的:这取决于我创建对象的顺序,把箭放在射弹之后修正了这个问题。你能解释一下什么被改变了吗?我相信问题在于物体被创造的顺序。是的,顺序很重要。确保在函数定义之后创建原型。这无关紧要,因为函数声明是被提升的。据我所知,您不需要更改任何内容,因为问题中的代码已经在运行。
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();