javascript - JS 中继承不起作用?

标签 javascript

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

收到此错误:

    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/

相关文章:

javascript - 如何在 PaperJS 中将图像添加到路径

javascript - 一张幻灯片中的多个图像

javascript - Bootstrap 中没有 href 的“a”链接

javascript - 开 Jest : How to teardown after (just) an individual test

javascript - D3.js 创建动态 color() 函数

javascript - 如何在javascript中杀死一个进程?

javascript - viewModel 使用 knockout.js 在原型(prototype)上计算函数

javascript - mapDispatchToProps 未将 actionCreators 分派(dispatch)到所需组件

javascript - karma-jasmine 无法读取属性 'clearTimeout'

javascript - 如何在 jquery 中使用 javascript 变量