内回调时使用此jQuery访问对象上下文
让我们假设我定义了以下对象:
Let us presume I have the following object defined:
var myObj = function(){
this.hello = "Hello,";
}
myObj.prototype.sayHello = function(){
var persons = {"Jim", "Joe", "Doe","John"};
$.each(persons, function(i, person){
console.log(this.hello + person);
}
}
问题是$ .each里面是人,但是我想访问obj属性hello.
Problem is that inside $.each this refers to person but I would like to access the obj property hello.
我能找到的唯一解决方案是在sayHello函数中声明类似
The only solution which i could find was declaring in sayHello function something like
var _this = this;
var _this = this;
然后在$ .each中,我将使用类似
and then in $.each i would use something like
console.log(_this.hello + person);
但是不幸的是,这不是很好的代码.还有另一种方法可以优雅地解决此问题吗?
But unfortunately, this is not very good code. Is there another way to resolve this problem elegantly ?
这似乎不是一个糟糕的解决方案...也许您会对使用Function.bind感兴趣(请参阅
That doesn't seem to be a bad solution... Perhaps you would be more interested in using Function.bind (see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind#Compatibility for compatibility), but that leads to counter-performance...
var myObj = function(){
this.hello = "Hello,";
}
myObj.prototype.sayHello = function(){
var persons = ["Jim", "Joe", "Doe","John"];
$.each(persons, function(i, person){
console.log(this.hello + person);
}.bind(this) );
}
另一种解决方案是声明一个变量并将其值设置为this.hello,如下所示:
Another solution is to declare a variable and set its value to this.hello, like this :
var myObj = function(){
this.hello = "Hello,";
}
myObj.prototype.sayHello = function(){
var persons = ["Jim", "Joe", "Doe","John"],
hello = this.hello;
$.each(persons, function(i, person){
console.log(hello + person);
});
}