2011-01-31 8 views
0

誰でも私が間違っていることを教えてもらえますか? HERESにコードを継承は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

+1

問題は何? – Pointy

+0

問題を追加しました。 – CyanPrime

答えて

2

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

を試してみてくださいあなたは、親のコンストラクタを呼び出すようにしたいが、それは "この" オブジェクトに適用されています。あなたがハードコーディングの関係を気にしない場合にも、直接シングを使用することができます。

Thing.call(this,x,y) 
1

控えめな継承を作成しないでください。プロトタイピングや機能的なアプローチで問題を解決することができるほとんどの状況ではほとんど意味がありません。

最良のアプローチは、各プレイヤーにxとyの取得/設定を持つcoordsオブジェクトを持たせるように構成状況を作成することです。

+0

オブジェクトの構成、クロージャの、mixinと['underscore.js'](http://documentcloud.github.com/underscore/)はあなたの友人です。プロトタイプは過大評価されています。 – Raynos

+0

@Raynos _ envangelismにどれだけお金を払っていますか? :P –

+0

私は他のオプションのどれよりも強く2番目の方法を強くお勧めします。プロトタイピングが過大評価されていることに同意します。私は、システムタイプの拡張メソッドのために個人的にしか使用しません。 –

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)); 
} 

ここでは、継承の代わりにオブジェクトの構成を使用します。代わりに、委任してPlayerにプライベートポジションオブジェクトを持たせることもできます。

また、getterとsetterを内部的に使用する場合はObject.definePropertyの使用をお勧めします。それはC#Propertyのようなものです。

_.extendObject.defineProperty

関連する問題