I’m a newbie trying to understand the value of this
, when adding a new property and a new method.
Adding new property:
const Person = function (fname, lname) {
this.fname = fname;
this.lname = lname;
};
const bob = new Person('Bob', 'Sinclair');
bob.fullName = `${this.fname} ${this.lname}`
in this example,
this
will refer to the global object, therefore the value of fullName
will be undefined
. I get it.
Adding new method:
bob.printFirstName = function () {
console.log(this.fname);
}
now, why is this
equal to the object? why, since is a function, is not equal to the global object or undefined (depending we are in non-strict/strict mode), Because is it a method? therefore the this
in a method is equal to the object? I don’t get it.