admin管理员组文章数量:1332628
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?
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?
Share Improve this question asked Jan 3, 2011 at 12:22 Atilla FilizAtilla Filiz 2,4328 gold badges31 silver badges49 bronze badges1 Answer
Reset to default 9What 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';}
本文标签: oopDefining Javascript class prototype methodsStack Overflow
版权声明:本文标题:oop - Defining Javascript class prototype methods - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742214115a2434253.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论