如何访问滚动事件中的对象范围

How to access object scope inside scroll event?

本文关键字:事件 对象 范围 滚动 何访问 访问      更新时间:2023-09-26

我有一个函数foo,它是在window.scroll上调用的。我想访问foo中的对象变量,例如,我想从父对象打印hello的值。

jsfiddle链接

 var Object = {
 hello: "hello",
  foo: function(e){
      alert(this.hello); //Prints undefined! I want to get this.hello
  },
  scrollListener: function(){
    var _this = this;
    $(window).scroll(_this.foo);
  },
};

我认为用匿名函数包装_this.foo就可以了。

在窗口中使用。滚动

$(window).scroll(function(){
      _this.foo();
});

DEMO

有2个解决方案

1) 使用$.proxy来完成该技巧。

$(window).scroll( $.proxy(_this.foo,this) );

演示

2) 返回foo函数,然后调用它。

foo: function(context) {
    var that = context;
    return function(e){ alert(that.hello); }
},
scrollListener: function(){
   var _this = this;
   $(window).scroll(_this.foo(_this));
},

演示