2014-08-29 25 views
2

我有一個功能foo它在window.scroll上被調用。我想訪問foo中的對象變量,例如我想從父對象打印hello的值。如何在滾動事件中訪問對象作用域?

jsfiddle link

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); 
    }, 
}; 
+0

根據的jsfiddle,調用時使用的代碼是正確的'Object.foo({});從'' – Mic1780 2014-08-29 17:03:23

+0

刪除'.hello' this',你就會明白爲什麼。在你的上下文中''this''指'窗口' – 2014-08-29 17:04:02

+0

我明白爲什麼這不可用。 'this'指的是滾動事件 – Anenth 2014-08-29 17:10:01

回答

2

我認爲,在一個匿名函數包裝_this.foo會做的伎倆。

使用這window.scroll

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

DEMO

0

有2個解決方案

1)使用$.proxy這樣的伎倆。

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

DEMO

2)返回FOO函數然後調用它。

foo: function(context) { 
    var that = context; 
    return function(e){ alert(that.hello); } 
}, 

scrollListener: function(){ 
    var _this = this; 
    $(window).scroll(_this.foo(_this)); 
}, 

DEMO

相關問題