定义Javascript类原型方法

时间:2011-01-03 12:22:19

标签: javascript oop prototype

我最初定义了这样一个类:

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

当我尝试创建对象时抛出异常:

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

在Chromium中并在Firefox中无声地失败(使用firebug)

这样可以正常工作:

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

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

在体内实现原型方法的正确方法是什么?

1 个答案:

答案 0 :(得分: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';}
相关问题