2

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.

0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

It might be helpful to include some info as to why using prototypes is better than the second way.
Added reference. Thanks for the suggestion.
I was looking for the alternate way, I knew I could do it using prototype but I didn't want the function to be in the prototype of the object as it doesn't make sense in my case, Thanks
I added info regarding bind. You can achieve the same context (that's the extent of it) using bind(this). On a second note this question is not a duplicate as it does not ask for oop strictly in the manner that the referenced question is set.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.