0

Going through some online resource I've came across these examples:

In this case this properties can be accessed via this.property method and this['property'], but can't be accesed using this[property]

function showFullName() {
  alert( this.firstName + " " + this.lastName );
}

var user = {
  firstName: "Alex",
  lastName: "Graves"
};

showFullName.call(user) 


In the following example accessing the properties using this.property and this['property'] leads to undefined.

var user = {
  firstName: "Alex",
  surname: "Graves",
  secondSurname: "Martinez"
};

function showFullName(firstPart, lastPart) {
  alert( this[firstPart] + " " + this[lastPart] );
}

showFullName.call(user, 'firstName', 'secondSurname') 


Can you please clarify a bit the behavior of dot and square brackets?

dutop
  • 59
  • 1
  • 5
Adrian
  • 273
  • 2
  • 13
  • 2
    The second example works, or are you expecting anything else? – Leon Adler Apr 28 '16 at 15:50
  • @LeonAdler I do apologize for the confusion, I did expect some explanations or maybe some external resources about the difference and behavior of accessing the properties of objects. – Adrian Apr 28 '16 at 15:58
  • The only difference is that string literals, as used in brackets, can contain characters that a property written using dot notation can't contain, otherwise they are basically the same. – adeneo Apr 28 '16 at 16:00

0 Answers0