marcos.borunda
marcos.borunda

Reputation: 1486

How to call a prototype function inside another prototype function without losing context

I have this CODE:

var MyObj = (function() {
    //Constructor
    var MyObj= function(){
        this.myArray = [1,2,3];
    }

    MyObj.prototype = {
        myFunc: function(){
            alert(this.myArray.toString());                
        },
        myFuncCaller: function(){            
            MyObj.prototype.myFunc();                
        }
    };
    return MyObj;      
})();

var myObj = new MyObj();
myObj.myFunc();

//This line will throw an exception because this.myArray is undefined
myObj.myFuncCaller();

​ Why is this.myArray undefined? I know I'm doing something wrong, how would be the correct way to do it?

Upvotes: 0

Views: 50

Answers (1)

SLaks
SLaks

Reputation: 887657

Just use this:

this.myFunc();

When you call a function in Javascript, this is set to the expression you called it on.
In your code, for example, this in myFunc() is MyObj.prototype.

Upvotes: 4

Related Questions