Karl Morrison February 2016

Pros and cons of this.myVar vs. var myVar

var MyFunction = function () {
    this.myVar = 'something';
    var myVar = 'else';
};

What are the pros and cons of the two above, I see them being used.

Answers


noa-dev February 2016

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.


Robin van den Berg February 2016

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.

Post Status

Asked in February 2016
Viewed 3,566 times
Voted 5
Answered 2 times

Search




Leave an answer