D.Breen
D.Breen

Reputation: 51

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.

Upvotes: 1

Views: 361

Answers (3)

ASDFGerte
ASDFGerte

Reputation: 5195

  • this.name refers to the property "name" of the current object that "this" represents
  • name is the parameter of the function.

As others already showed, the value of this.name could be changed by other instructions outside of the function you declare by changing the property on the object, while using name means you are closing over the parameter (which could in case of strings not be manipulated from outside the declared function, except maybe for freak cases)

Secondly, you assign this.name = name, but even that operation can "fail" (not do what might be intended, as in "change the value returned by this.name"). E.g. when you call the function with this set to an object that has a setter for the "name" property which is not trivial. That can happen even without any extra declared functions:

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

let obj = { set name(val) { }, get name() { return "unintended"; } };
Person.call(obj, "intended");

Upvotes: 1

Ayan
Ayan

Reputation: 2380

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

Upvotes: 6

Hardy
Hardy

Reputation: 5631

It doesn't matter witch one you use.. this.name just assings the name variable into to your "class person" so you can use that variable in other functions inside your class.

Upvotes: -1

Related Questions