2011-01-03 18 views
4

は、私が最初にこのようなクラスを定義した:Firefoxで静か定義Javascriptのクラスのプロトタイプメソッド

t=new mapTile(1,1) 
TypeError: Cannot set property 'visible' of undefined 

クロム中と失敗します。私は、オブジェクトを作成しようとすると例外をスロー

function mapTile(nx,ny) 
{ 
    //members 
    this.x = nx; 
    this.y = ny; 

    //methods 
    this.prototype.visible = function(){return true;}; 
    this.prototype.getID = function(){return y*tiles_per_line+x;}; 
    this.prototype.getSrc = function(){return 'w-'+this.getID+'.png';} 
}; 

(放火魔で)これはOKかの作品:

function mapTile(nx,ny) 
{ 
    //members 
    this.x = nx; 
    this.y = ny; 
}; 

//methods 
//this.prototype.xx=1; 
mapTile.prototype.visible = function(){return true;}; 

体内にプロトタイプメソッドを実装する適切な方法は何ですか?

答えて

9

体内のプロトタイプのメソッドを実装するための適切な方法は何ですか?

あなたはこの答えを好きではないことがあります。それは彼らにコンストラクタは、そのオブジェクトに対して実行するたびに再定義するので、は、体内にそれらを定義していません。あなたが働いているように、それが宣言された後にobjectType.prototype...と定義します。

プロトタイプメソッドは、すべてのインスタンス間で共有するために特別にありますが、何をやっていると、どこかで-の間で、あなたはそれらは、このように、そのインスタンスに固有の内部で宣言したいのいずれか:

function mapTile(nx,ny) 
{ 
    //members 
    this.x = nx; 
    this.y = ny; 

    //methods 
    this.visible = function(){return true;}; 
    this.getID = function(){return y*tiles_per_line+x;}; 
    this.getSrc = function(){return 'w-'+this.getID+'.png';} 
} 

または共有

function mapTile(nx,ny) 
{ 
    //members 
    this.x = nx; 
    this.y = ny; 
} 
mapTile.prototype.visible = function(){return true;}; 
mapTile.prototype.getID = function(){return y*tiles_per_line+x;}; 
mapTile.prototype.getSrc = function(){return 'w-'+this.getID+'.png';} 
+0

私はそれほど好きではありませんでしたが、あなたはポイントがあります。 –

関連する問題