通过使用点或方括号访问对象属性来混淆

时间:2016-04-28 15:48:10

标签: javascript properties square-bracket

通过一些在线资源,我发现了这些例子:

在这种情况下可以通过this.property方法和this['property']访问此属性,但无法使用this[property]

进行访问
function showFullName() {
  alert( this.firstName + " " + this.lastName );
}

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

showFullName.call(user) 


在以下示例中,使用this.propertythis['property']访问属性会导致undefined

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

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

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

你能否澄清点和方括号的行为?

0 个答案:

没有答案