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.

Snedden27
  • 1,870
  • 7
  • 32
  • 60

1 Answers1

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.

Community
  • 1
  • 1
Schahriar SaffarShargh
  • 1,971
  • 2
  • 16
  • 24
  • It might be helpful to include some info as to why using prototypes is better than the second way. – forgivenson Nov 07 '15 at 23:16
  • Added reference. Thanks for the suggestion. – Schahriar SaffarShargh Nov 07 '15 at 23:19
  • 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 – Snedden27 Nov 07 '15 at 23:21
  • 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. – Schahriar SaffarShargh Nov 07 '15 at 23:23