Search code examples
javascriptthisjavascript-objectsvar

Is var variable different from this in JavaScript


I have a bit of a confusion on the term var and declaring a variable with keyword this in a JavaScript constructor function. For example, in the code below, is var title a different variable than happySongs[0].title. They are both initialized with something different. title is initialized in the constructor to song parameter and title is also initialized outside the constructor function. However, they both return something different. If you print out happySongs[0].title it gives you the new value. However, if you print out the concat() method, title will not have the new value of 'test', but rather the old one.... So there are two different things going on here? Are these separate variables? Is there a difference when you declare a variable with var and this inside a function constructor?

function Tune(song,artist) {
  var title = song;
  this.concat = function() {
   return title + " " + artist;
 }
}

var happySongs = [];
happySongs[0] = new Tune("Putting on the Ritz", "Ella Fitzgerald");

happySongs[0].title = 'test'
//prints out test
console.log(happySongs[0].title); 

 // prints out correct title and artist
console.log(happySongs[0].concat());

Solution

  • They are different.

    var title = song;
    

    Is a locally scoped variable within the constructor function.

    happySongs[0].title = 'test'
    

    Is creating a title property on the constructed Tune object. Changing one will have no affect on the other. The concat function, being declared within the constructor function, has access to the locally scoped title variable declared in the outer scope. If you reference this.title instead, you would get the property:

    this.concat = function() {
      return this.title + " " + artist;
    }
    

    The above, if placed in your original code, would cause the final line:

    console.log(happySongs[0].concat());
    

    To output "test Ella Fitzgerald".