“this”指向窗口,而不是指向回调函数后的原型函数

时间:2016-02-27 09:26:11

标签: javascript callback prototype this

我有这个原型功能

    getSupportActionBar().setBackgroundDrawable(<create a background drawable with solid rectangle and color as what you want>);

并从此页面优化滚动 https://developer.mozilla.org/en-US/docs/Web/Events/resize(我只用滚动更改了调整大小)

(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");
});

当我滚动时执行回调函数,但是我对小字“this”有疑问。我怎么能得出“这个”指的是我的obj而不是窗口。我玩“打电话”,但我没有得到它......

格里

1 个答案:

答案 0 :(得分:0)

@MysterX的评论是正确的;)

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

不是“打电话”我试过的东西

谢谢! ;)