How to reference to outer member
Given following JavaScript code:
({
foo: 1,
bar: 2,
zoo: 3,
test: function(i) {
var g = function(i) {
alert(i + zoo);
}
g(i);
}
}).test(2);
Why is zoo undefined in alert() ? Which kind of syntax can I use to correctly reference to zoo and get alert display for value 5 ?
Update: I would prefer solution where only implementation of g needs to change, if at all possible.
zoo is not a free floating variable, it's a property of the object. Inside test you can reference the object using this (because of the way you call it). Inside g the this context will be lost though, so you need to explicitly preserve it:
test: function(i) {
var g = function(i) {
alert(i + this.zoo);
}.bind(this);
g(i);
}
or:
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);
When you invoke a member function of an object, the this keyword is set to the object (unless you call the function using .call or .apply ). The function g is no longer a member of the object, so this is not set to the object. You have a couple of options if you want to keep using the g function.
Set a reference to this :
test: function(i) {
var that = this;
var g = function(i) {
alert(i + that.zoo);
}
g(i);
}
or manually set the value of this by using .call
test: function(i) {
var g = function(i) {
alert(i + this.zoo);
}
g.call(this, i);
}
Here's a little more info about .call and .apply.
链接地址: http://www.djcxy.com/p/94914.html上一篇: 不能从方法访问NavController
下一篇: 如何引用外部成员
