var MyFunction = function () {
this.myVar = 'something';
var myVar = 'else';
};
What are the pros and cons of the two above, I see them being used.
var MyFunction = function () {
this.myVar = 'something';
var myVar = 'else';
};
What are the pros and cons of the two above, I see them being used.
The main difference is following:
var myFunc = function(){
this.x = 2; // You want this to be used outside of the declaration
}
var y = new MyFunc();
console.log(y.x); // 2
var myFunc2 = function(){
var x = 3; // you only want to use it inside this function
}
var z = new MyFunc2();
console.log(y.x); // undefined
So the this. variable will be accessible and the var won't be.
Use this.myVar when you want to indicate that it is a variable that acts as a property of MyFunction.
Consider:
var MyFunction = function () {
this.myVar = 'something';
var myVar2 = 'else';
};
then
myF = new MyFunction()
Note that you can now access myF.myVar (as property), but not myVar2.