Defining Javascript Class Prototype Methods

First I defined a class like this:

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

What throws an exception when trying to create an object:

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

in Chromium and not working quietly in Firefox (with firebug)

This works fine 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 correct way to implement prototypes inside the body?

+4
source share
1 answer

What is the correct way to implement prototypes inside the body?

You may not like this answer: do not define them inside the body, as this will override them every time the constructor works for this object. Define them how you work with objectType.prototype... after the declaration.

Prototype methods are specifically designed to be shared among all instances, what you are doing is somewhere in the middle, you either want them to be declared inside a particular instance, for example:

 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, for example:

 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';} 
+9
source

Source: https://habr.com/ru/post/1334060/


All Articles