Jquery 将对象传递到$(window.bind()中

Jquery 将对象传递到$(window.bind()中,jquery,function,object,scope,Jquery,Function,Object,Scope,我有一个通用(自定义)jQuery插件。$。fn.某物()。这会在我的DOM中的某些对象上调用。比方说 $('div.section').something() 在函数内部,我有这样的东西 $.fn.something = function(options) { //here **this** refers to $('div.section') which is what I want $(window).bind('scroll', function(){

我有一个通用(自定义)jQuery插件。$。fn.某物()。这会在我的DOM中的某些对象上调用。比方说

$('div.section').something()
在函数内部,我有这样的东西

$.fn.something = function(options) {

    //here **this** refers to $('div.section') which is what I want

    $(window).bind('scroll', function(){
        //how do I get the 'this' from above into here.
    });

});
我一生都无法从.bind()函数中的插件中获得对“this”的引用。我有一个变通方法,将“this”存储到options数组中并以这种方式传递,但我不禁想到有一种更直接的方法可以做到这一点

使用变量

$.fn.something = function(options) {

    var self = this;

    $(window).bind('scroll', function(){
        //use self.options
    });

});

这是我从knockoutjs中学到的一个技巧

在变量中设置
This
的值,然后使用它来代替

$.fn.something = function(options) {

    var that = this;

    $(window).bind('scroll', function(){
        // use that!
    });

});
这看起来像是一个黑客,但这是一个非常常见的地方

如果您能够使用ES5中介绍的方法,而不必担心,那么您也可以使用该函数

$(window).bind('scroll', (function(){
    // use this
}.bind(this)));
使用$.proxy:

$.fn.something=函数(选项){


}))

太好了,这足以让我安心。非常感谢各位。
$.fn.something = function(options) {

    var self=this;

    $(window).bind('scroll', function(){
        //you can now use self
    });

});
$(window).bind('scroll', $.proxy(function(){
    //you can now use this
}, this));