开发者

Defining Javascript class prototype methods

I defined a class like this at first:

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

Which throws an exception when I try to create an object:

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

in Chromium and fails silently in Firefox(with firebug)

This works OK though:

开发者_高级运维
function mapTile(nx,ny)
{
    //members
    this.x = nx;
    this.y = ny;
};

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

What is the proper way to implement prototype methods inside the body?


What is the proper way to implement prototype methods inside the body?

You may not like this answer: don't define them inside the body, since that would re-define them every time the constructor runs for that object. Define them like you have working, with objectType.prototype... after it's declared.

Prototype methods are there specifically to be shared amongst all instances, what you're doing is somewhere in-between, you either want them declared inside specific to that instance, like this:

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

Or shared on the prototype outside, like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜