D.Breen D.Breen - 3 months ago 8
Javascript Question

Why Should I use `this.name` instead of `name` in Person Constructor (and similar constructors)?

Simple question. Why should I do this...

var Person = function(name) {
this.name = name;
this.sayHello = function(){
console.log('Hello, my name is ' + this.name); // <--
}
};


instead of...

var Person = function(name) {
this.name = name;
this.sayHello = function(){
console.log('Hello, my name is ' + name); // <--
}
};


I haven't found a situation that they behave differently.

Answer

So if there is any function reseting the name, things wont get refelected if you aint using this.name. Check this example

var Person = function(name) {
  this.name = name;
  this.sayHello = function() {
    console.log('Hello, my name is ' + name);
    console.log('Hello, my name is ' + this.name);// <--
  }
};
Person.prototype.resetName = function(name) {
  this.name = name;
}

var me = new Person('A');
me.sayHello();
console.log('******');
me.resetName('Ayan');
me.sayHello();