Hi,
As some you know, I am trying to learn JavaScript from the book… In a chapter, there is this example:
let person = {
getName: function () {
return "The Name is " + this.firstName + " " + this.lastName;
},
getInitials: function () {
if (this.firstName && this.lastName) {
return this.firstName[0] + this.lastName[0];
}} };
let funnyGuy = Object.create(person);
funnyGuy.firstName = "Conan";
funnyGuy.lastName = "O'Brien";
console.log(funnyGuy.firstName);
I am not trying to get out of using the “this” keyword, but it seems as though that it might be easier to simply define the variables (firstName and lastName) at the beginning of the object and re-value them with the new values of the new objects; I think this method is a bit more intuitive. Like:
let person2 = {
firstName: null,
lastName: null,
getName: function () {
return "The Name is " + this.firstName + " " + this.lastName;
},
getInitials: function () {
if (this.firstName && this.lastName) {
return this.firstName[0] + this.lastName[0];
} } };
let funnyGuy2 = Object.create(person2);
funnyGuy2.firstName = "Ike";
funnyGuy2.lastName = "777";
console.log(funnyGuy.firstName); // The result is Identical!
Is there an advantage to using the “this” keyword that I am not able to appreciate right now?