我最近开始学习 JavaScript,想知道是否可以在同一个对象中直接在函数中使用对象变量。这是到目前为止我的代码。
var user = {
name: 'Example',
age: 687,
address: {
firstLine: '20',
secondLine: 'St Fake',
thirdLine: 'Fakeland'
},
logName: function(inputName, inputAge){
console.log(user.name);
console.log(user.age);
console.log(inputAge);
console.log(inputName);
}
};
user.logName('Richard', 20);
如何在函数中链接到用户的姓名和年龄变量,而不需要在变量上添加对象名称前缀?
最佳答案
在 most cases ,您可以只使用 this
keyword获取您的函数作为方法被调用的对象。在您的示例中:
var user = {
name: 'Example',
age: 687,
address: {
firstLine: '20',
secondLine: 'St Fake',
thirdLine: 'Fakeland'
},
logName: function(inputName, inputAge) {
console.log(this.name);
// ^^^^
console.log(this.age);
// ^^^^
console.log(inputAge);
console.log(inputName);
}
};
user.logName('Richard', 20); // method call on `user`,
// so `this` will become the `user` in the function
关于javascript - 在函数内使用对象变量。 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26196182/