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?
Just use
this:When you call a function in Javascript,
thisis set to the expression you called it on.In your code, for example,
thisinmyFunc()isMyObj.prototype.