【发布时间】:2016-02-27 09:26:10
【问题描述】:
我有这个原型功能
(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”这个小字有疑问。我怎样才能实现“this”指的是我的 obj 而不是窗口。我玩过“呼叫”,但我没听懂...
格雷戈
【问题讨论】:
-
传递回调时,使用callback.bind(this)
标签: javascript callback prototype this