如何引用外部成员
鉴于以下JavaScript代码:
({
foo: 1,
bar: 2,
zoo: 3,
test: function(i) {
var g = function(i) {
alert(i + zoo);
}
g(i);
}
}).test(2);
为什么zoo在alert()未定义? 我可以使用哪种语法来正确引用zoo并获得值为5警报显示?
更新:如果可能的话,我更喜欢只需要改变g实现的解决方案。
zoo不是一个自由浮动变量,它是对象的一个属性。 在test你可以使用this参考对象(因为你调用它的方式)。 在g内部, this上下文将会丢失,所以你需要明确地保存它:
test: function(i) {
var g = function(i) {
alert(i + this.zoo);
}.bind(this);
g(i);
}
要么:
test: function(i) {
var g = function(i) {
alert(i + this.zoo);
};
g.call(this, i);
}
使用箭头功能保留的“外部”值this ,并用它来访问的价值zoo属性:
({
foo: 1,
bar: 2,
zoo: 3,
test: function(i) {
var g = i => alert(i + this.zoo);
g(i);
}
}).test(2);
当调用的对象的成员函数,在this关键字被设置到对象(除非使用调用函数.call或.apply )。 函数g不再是对象的成员,所以this不会设置为该对象。 如果你想继续使用g函数,你有几个选项。
设定为参考this :
test: function(i) {
var that = this;
var g = function(i) {
alert(i + that.zoo);
}
g(i);
}
或手动设定的值this通过使用.call
test: function(i) {
var g = function(i) {
alert(i + this.zoo);
}
g.call(this, i);
}
这里有一些关于.call和.apply的更多信息。
链接地址: http://www.djcxy.com/p/94913.html