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

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

basickarl
  • 37,187
  • 64
  • 214
  • 335
  • 1
    They're just different things. It's like asking the pros and cos of numbers vs strings. – Álvaro González Feb 08 '16 at 12:49
  • @ÁlvaroGonzález If you could give scenarios it would help as both can be used inside of the function just as well. – basickarl Feb 08 '16 at 12:50
  • 3
    They are not interchangeable options, they do quite different things, so a pros and cons list doesn't really make sense. – nnnnnn Feb 08 '16 at 12:51
  • 1
    It is not about pros and cons. It is about design, namely [Open/Closed Principle](https://en.wikipedia.org/wiki/Open/closed_principle) and [Encapsulation](http://stackoverflow.com/a/18557503/343721). The latter link describes the third option you might find useful: properties. – Jan Turoň Feb 08 '16 at 12:59

2 Answers2

0

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.

noa-dev
  • 3,561
  • 9
  • 34
  • 72
0

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.

  • *"it is a variable that acts as a property of MyFunction"* - It's *not* a property of MyFunction, it's a property of whatever object `this` refers to when the function runs - which could be any object depending on how MyFunction was invoked. – nnnnnn Feb 08 '16 at 12:57