When should you use this.x vs var x?

When creating a function of the javascript class I often use this.. But using this, he makes me wonder if this would not have changed instead of using var.

var myClass = function() {
    this.x = 4;
    return {
        getVal: this.x
    };
}

against the same using var

var myClass = function() {
    var x = 4;
    return {
        getVal: x
    };
}

What is the difference and when should I use them?

+5
source share
4 answers

Variables with thisbecome publicvariables, and those with which varbecome variables private.

, this, , , . this, , new, .

:

function Foo() {
  // private var
  var bar = 'I am bar';
  // public var
  this.baz = 'I am baz';
}

var f = new Foo;
console.log(f.bar); // undefined
console.log(f.baz); // I am baz

javascript . . , , var .

, this, , . , .

+7

this.x myClass.x, var x. .

+1

, ( var) ( ) .

, :

  • "this", "new", .call, .

  • , ( - , )

  • Variables declared with "var" are private and cannot be accessed outside the function. Sometimes this is normal, but it may prevent you from doing inheritance (no concept of "protected in Javascript")

+1
source

this:xlook like instance variables. These variables have a common scope. works like class variables in OOP.

Although it var x;has a limited scope. These variables behave as private variables and are available in the local area.

+1
source

All Articles