我最近开始学习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/