gpt4 book ai didi

javascript - JS 中继承不起作用?

转载 作者:行者123 更新时间:2023-11-28 21:26:43 24 4
gpt4 key购买 nike

谁能告诉我我做错了什么?

收到此错误:

    this.parent.Thing is not a function
this.parent.Thing(x,y);

这是代码。

[Break On This Error] this.parent.Thing(x,y); 

//Thing class start
function Thing(x, y){
this.x = x;
this.y = y;
}

Thing.prototype.setX = function(newX){
this.x = newX;
}

Thing.prototype.setY = function(newY){
this.y = newY;
}

Thing.prototype.getX = function(){
return this.x;
}

Thing.prototype.getY = function(){
return this.y;
}
//Thing class end


//player start
Player.prototype = new Thing();
Player.prototype.constructor=Player; // Otherwise instances of Cat would have a constructor of Mammal
Player.prototype.parent = Thing.prototype;

function Player(x, y){
this.parent.Thing(x,y);
}

//player end


var player = new Player(100,100);

最佳答案

尝试

this.parent.constructor.call(this,x,y);

您想要调用父级的构造函数,但将其应用于“this”对象。如果您不介意对关系进行硬编码,您也可以直接使用 Thing:

Thing.call(this,x,y)

关于javascript - JS 中继承不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4855076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com