我使用顯露模塊模式的一些畫廊代碼:這等於窗口requestAnimationFrame回調
window.jdiGallery = (function() { //Structure from http://code.tutsplus.com/tutorials/build-your-first-javascript-library--net-26796
var instance = null;
function Gallery (nodeList, options) {
this.settings = this.extend({
'transitionSpeed': 100, //in ms
'slideSpeed': 5000
}, options);
this.requestAnimationId; //We need this handle for canceling the RAF
this.start = null; //To help determine how far we are between transitions
for(var i = 0; i < nodeList.length; i++)
this.instances[i] = this.init(nodeList[i]);
}
Gallery.prototype.init = function(el){
var slideEls = el.querySelectorAll('* > .nd-slide');
var slides = [];
//this is equal to the Gallery instance
for(var i = 0; i < slideEls.length - 1; i++)
slides.push(new Slide(slideEls[i], i, this.settings["inTransition"], this.settings["outTransition"]));
}
Gallery.prototype.moveToNext = function(timestamp){
var progress;
if (this.start === null) //this is equal to window
this.start = timestamp;
progress = timestamp - this.start;
if (progress > 5000) {
console.log('moving to next');
this.start = null;
requestAnimationFrame(this.moveToNext);
}
}
return {
create: function (selector, options) {
//creation code omitted for brevity
instance = new Gallery(els, options);
this.requestId = window.requestAnimationFrame(instance.moveToNext);
},
當create
被調用,它最終調用Gallery.init()
。在該函數中,this
等於Gallery
的實例。
然後我通過Gallery.moveToNext()
作爲回調我的requestFrameAnimation
。當我們進入moveToNext
時,this
的值是window
。爲什麼它沒有像我期望的那樣引用Gallery
?
+1這個答案肯定比我的好 – slezica