I have JavaScript function as object:
function hexMesh(){
var side=25;
console.log('hexMesh');
function drawOver(){
}
}
As you can see it has a function call drawOver
.
I try to call it by using a constructor as follows:
window.onload = function() {
hexMeshObj=new hexMesh();
hexMeshObj.drawOver();
}
But it gives me error saying undefined is not a function
Now I know I could declare the function in the prototype of the object but I don't want to do that.
Here it is on JSFiddle.
You can't use JavaScript like that!
Solution: Use Class-like prototypes (please don't treat them as classes, although they provide inheritance)
var x = function(v){ this.test = v; } // This is your constructor
x.prototype.show = function(){ console.log("TEST", this.test); } // This is a prototype with this as a context
var y = new x(true);
y.show(); // Logs TEST true
Edit: Alternatively (although the prototype way is better as it provides real inheritance the oop way)
var x = function(v){
var context = this;
this.test = v;
this.show = function(){
console.log('test', context.test)
});
Another alternative way is to use bind to bind context if you need it.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments