[JS] Confused how to retrieve variable value from within a function

Started by
1 comment, last by hdnine 11 years, 5 months ago
I'm having problems seeing how to solve the particular issue of returning the tile size to the caller. I have my own namespace called "goon" where i've added different functions, for example Tile below which i use to build my level. If i try:

console.log(goon.Tile.size); // This returns undefined.
console.log(goon.Tile.getTileSize()); // Throws the error: goon.Tile.getTileSize is not a function

[source lang="jscript"]goon.Tile = function(type, col, row) {
this.type = type;
this.size = 30;
this.top = row * this.size;
this.left = col * this.size;
this.bottom = row * this.size + this.size;
this.right = col * this.size + this.size;
this.getTileSize = function() {
return this.size;
};
}[/source]

So i tried adding a prototype and removed the above but this till doesn't work so obviously i'm doing something wrong here. I just need to get the size value from the function, is this even possible?

[source lang="jscript"]goon.Tile = function(type, col, row) {
this.type = type;
this.size = 30;
this.top = row * this.size;
this.left = col * this.size;
this.bottom = row * this.size + this.size;
this.right = col * this.size + this.size;
}

goon.Tile.prototype.getTileSize = function() {
return this.size;
};[/source]

Is the problem that i need to invoke or call the function first? Maybe you can't have a function within a function. Anyway, any help would be apprecieated.
Advertisement
goon.Tile is a class, not an object.
"this" is applied on object, as far as I understand.
You need to write as,

function TileClass(blah) {
this.type = type;
// blah
}

goon.Tile = new TileClass(blah).

https://www.kbasm.com -- My personal website

https://github.com/wqking/eventpp  eventpp -- C++ library for event dispatcher and callback list

https://github.com/cpgf/cpgf  cpgf library -- free C++ open source library for reflection, serialization, script binding, callbacks, and meta data for OpenGL Box2D, SFML and Irrlicht.

Right... will give it a try. Thanks!

This topic is closed to new replies.

Advertisement