我习惯了Mootools,它有一个绑定方法。 据我所知,JQuery的bind()用于事件。
所以,在一个类方法中,我习惯这样做:
$.each(items,function(index,item){
//[...] then here this refers to the class constructor, not item
}.bind(this));
我如何在JQuery中执行此操作?
答案 0 :(得分:2)
bind
是vanilla JS。
jQuery为没有bind
的非常旧的浏览器提供proxy功能(即I.E. 8 - )
请注意,具有bind
功能的浏览器也具有Array.prototype.forEach
功能,这使得$.each
通常无用。
你的$.proxy
循环,也在使用IE8:
$.each(items, $.proxy(function(index,item){
// here, this is the outside this
}, this));
答案 1 :(得分:0)
IE8答案来自:
// Credit to Douglas Crockford for this bind method
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError ("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call (arguments, 1),
fToBind = this,
fNOP = function () {
},
fBound = function () {
return fToBind.apply (this instanceof fNOP && oThis
? this
: oThis,
aArgs.concat (Array.prototype.slice.call (arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP ();
return fBound;
};
}