2011-01-31 61 views
0

谁能告诉我我做错了什么?继承不在JS中工作?

收到此错误:

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); 
+0

从这里得到它:http://phrogz.net/js/classes/OOPinJS2.html – CyanPrime 2011-01-31 19:26:29

+1

什么问题? – Pointy 2011-01-31 19:28:26

回答

2

尝试

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

你要调用父类的构造函数,但必须把它应用到了 “这个” 对象。您也可以直接使用的东西,如果你不介意硬编码的关系:

Thing.call(this,x,y) 
1

您应该避免不惜一切代价创建经典继承!在大多数情况下,当您可以采取原型和/或功能方法来解决任何问题时,这是毫无意义的。

最好的方法是创建一个组合情境,让每个玩家都有一个coords对象,该对象已经为x和y获取/设置。

0
var Position = function(x,y) { 
    var x = x; 
    var y = y; 
    if (Object.defineProperty) { 
     Object.defineProperty(this, "x", { 
      "enumerable": true, 
      "get": function() { return x; } 
     }); 
     Object.defineProperty(this, "y", { 
      "enumerable": true, 
      "get": function() { return y; } 
     }); 
    } else { 
     this.getX = function() { return x; } 
     this.getY = function() { return y; } 
    } 
} 

var Player = function(x,y) { 
    _.extend(this, new Position(x,y)); 
} 

这里我们用对象组合而不是继承。或者,您可以委托并让玩家拥有私人头寸对象。

另外我建议使用Object.defineProperty在内部使用getter和setter。这就像一个C#Property

_.extendObject.defineProperty