定义Javascript类原型方法

Ati*_*liz 4 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';}
};
Run Code Online (Sandbox Code Playgroud)

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

t=new mapTile(1,1)
TypeError: Cannot set property 'visible' of undefined
Run Code Online (Sandbox Code Playgroud)

在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;};
Run Code Online (Sandbox Code Playgroud)

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

Nic*_*ver 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';}
}
Run Code Online (Sandbox Code Playgroud)

或者在外面的原型上共享,像这样:

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';}
Run Code Online (Sandbox Code Playgroud)