我有以下对象:
myObject = {
color: "yellow",
age: 23,
nationality: "usa",
getAge: function(){
var age = 33;
alert(age);
}
}
我可以调用getAge()
方法
myObject.getAge();
我会在弹出窗口中得到 33。
我想通过更改对象 this 引用来在警报框中获取 23。我在想类似下面的事情
myObject.getAge.call(this);
我的理解是,通过将 this 传递给调用方法,我将 getAge()
方法中 this 的引用更改为myObject
的值,然后应该允许警报框返回 23。不幸的是,结果仍然是 33。
如何将 this 引用更改为 myObject
的引用?
最佳答案
myObject = {
color: "yellow",
age: 23,
nationality: "usa",
getAge: function(){
alert(this.age);
}
}
myObject.getAge();
使用构造函数可能会更好,因为 this 在那里被破坏了。请参阅有关 this
工作原理的任何其他答案。
function person(){
this.color = "yellow";
this.age = 23;
this.nationality = "usa";
}
person.prototype.getAge = function(){
alert(this.age);
};
var p = new person();
p.getAge();
关于javascript - 使用 Call 方法引用对象中的属性 - JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20667945/