2016-02-27 59 views
0

我有這個函數原型「這個」點窗口,而不是一個回調函數

(function(window, undefined){ 
    function Waypoint (el, callback, offset){ 
     this.el = el; 
     this.cb = callback; 
     this.offset = offset || 0; 
     window.optimizedScroll.add(this.passedWaypoint); 
     //window.optimizedScroll.add(this.passedWaypoint.call(this)); doesn't work 
    } 

    Waypoint.prototype.passedWaypoint = function(){ 
     //if element passes a point execute the callback function 
     //this.cb(); //undefined 
     console.log(this); //refers to window and not to my obj 
    }; 

    window.Waypoint = Waypoint; 

})(this); 

var myElement1 = new Waypoint("myElement", function(){ 
    console.log("i have traveled so far"); 
}); 

和這種優化的從這個頁面滾動後我的原型功能 https://developer.mozilla.org/en-US/docs/Web/Events/resize(我只改帶滾動調整)

var optimizedScroll = (function(window, undefined) { 
    var callbacks = [], running = false; 
    // fired on resize event 
    function scroll() { 
     if (!running) { 
      running = true; 
      window.requestAnimationFrame(runCallbacks); 
     } 
    } 
    // run the actual callbacks 
    function runCallbacks() { 
     callbacks.forEach(function(callback) { 
      callback(); 
     }); 
     running = false; 
    } 
    // adds callback to loop 
    function addCallback(callback) { 
     if (callback) { 
      callbacks.push(callback); 
     } 
    } 
    return { 
     // public method to add additional callback 
     add: function(callback) { 
      if (!callbacks.length) { 
       window.addEventListener('scroll', scroll); 
      } 
      addCallback(callback); 
     } 
    }; 
})(this); 

當我滾動時,回調函數被執行,但我有一個小字「this」的問題。我怎麼能得到這個「這個」是指我的obj而不是窗口。我與「呼」,但我沒有得到它發揮各地...

格雷戈爾

+1

可能重複[「this」關鍵字如何工作?](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – trincot

+1

當傳遞迴調時,使用callback.bind(本) – MysterX

回答

0

@MysterX的評論是正確的;)

window.optimizedScroll.add(this.passedWaypoint.bind(this)); 

不是「呼」是我的嘗試

謝謝! ;)

相關問題