The use of 'this' keyword in JavaScript (very basic question...) | SoloLearn: Learn to code for FREE!

0

The use of 'this' keyword in JavaScript (very basic question...)

what's the difference between these? //1. No use of 'this.' let person = { firstName: `Ryan`, lastName: `Christiani`, sayName() { return `Hi my name is ${person.firstName} ${person.lastName}`; } }; console.log(person.sayName()) //2. Using 'this.' let person = { firstName: `Ryan`, lastName: `Christiani`, sayName() { return `Hi my name is ${this.firstName} ${this.lastName}`; } }; console.log(person.sayName()) // the results were same, but should I use 'this.' ? those codes are from https://css-tricks.com/template-literals/ the second one is original codes. there's some reason to use this. ? which is better? https://www.w3schools.com/js/js_this.asp " The JavaScript this keyword refers to the object it belongs to. In an object method, this refers to the "owner" of the method. " so, I guess, the 'sayName()' method is inside the object 'person', so I should use 'this.firstname'? If I use 'person.firstname' then it is kind of unnecessary overlapping or something like that? thank you in advance

4/8/2020 4:34:08 AM

Goomba_duu

2 Answers

New Answer

+4

"This" is better. Without using "this" your method is restricted to an object named person. For example: let human = person; //same object person = undefined; //now only human console.log(human.sayName()) //error It's very probable that you want to extend your person object and use it as prototype (similar to a parent class) of another object (child).E.g: let kev = Object.create(person); kev.firstName = "Kevin"; But now kev.sayName() will return "Ryan" instead of the expected "Kevin". Using "this" allows you to use your method in any context. For example this won't work as expected if you don't use "this": let myAlienObject = { firstName : "$&#@", lastName : "Star" } let myFunction = person.sayName.bind(myAlienObject); myFunction();

+1

thank you very much (: