The problem is that myObject
is assigned AFTER calling MyObject
, so if inside it, myObject
is still undefined.
Some alternatives:
function MyObject(){
this.myVar = 500;
myFunction.call(this); // Pass object as `this`
}
function myFunction(){
alert(this.myVar);
}
var myObject = new MyObject();
or
function MyObject(){
this.myVar = 500;
myFunction(this); // Pass object as argument
}
function myFunction(obj){
alert(obj.myVar);
}
var myObject = new MyObject();
or
var myObject;
function MyObject(){
this.myVar = 500;
}
function myFunction(obj){
alert(myObject.myVar);
}
var myObject = new MyObject(); // Now myObject is set
myFunction(); // Call `myFunction` after `MyObject`, not inside it.
or
var myObject;
function MyObject(){
this.myVar = 500;
this.myFunction(); // Prototype method
}
MyObject.prototype.myFunction = function(){
alert(this.myVar);
}
var myObject = new MyObject();
or
var myObject;
function MyObject(){
var that = this;
function myFunction(){ /* Place myFunction inside MyObject. Note that this
way each instance will have a copy of myFunction */
alert(that.myVar);
}
this.myVar = 500;
myFunction();
}
var myObject = new MyObject();