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());