2016-05-15 67 views
0

我做一些锻炼; Tibial“本”方面,我有问题,在一个管法失去“这个”背景:失去对象的方法

function Main() { 
// something 
this.render = function() { 
    this.groups.forEach(function(g){ 
     renderGroup(g); 
    }); 
    return this; 
}; 
// something 
this.pipe = function() { 
    this.render();      // 1 
    requestAnimationFrame(this.pipe); // 2 
    return this; 
}; 
// something 
} 

Ad.1:这一事业“,这是不确定的,所以它没有渲染功能”

Ad.2:如果上面的评论,还是‘本’上下文未定义所以管不是一个函数

初始化:

function init() { 
    var m = new Main(); 
    requestAnimationFrame(m.pipe); 
} 

window.onload = function() { 
    init(); 
} 

完整的对象代码:

function Main() { 
this.canvas = document.createElement("canvas"); 
this.canvas.width = 1366; 
this.canvas.height = 768; 

this.canvas.style.width = this.canvas.width + "px"; 
this.canvas.style.height = this.canvas.height + "px"; 

this.groups = []; 
window.app = {}; 

this.grain = 30 * 1000 * 60; 
this.grainWidth = 30; 

this.getGroups = function() {return this.groups;} 
this.render = function() { 
    this.groups.forEach(function(g){ 
     renderGroup(g); 
    }); 
    return this; 
}; 

this.ctx = this.canvas.getContext("2d"); 
this.pipe = function() { 
    this.render();   
    requestAnimationFrame(this.pipe); 
    return this; 
}; 

document.body.appendChild(this.canvas); 

registerEvents(); 

} 

的renderGroup是纯的forEach。

是什么导致上下文丢失?

回答

1

简单地捆绑你想管与

this.pipe = function() { 
    this.render();      // 1 
    requestAnimationFrame(this.pipe); // 2 
    return this; 
}.bind(this) 
+0

这有效,但看看编辑。 –

1

也许这样的事情被称为上下文?

requestAnimationFrame(this.pipe.bind(this)); 

当JavaScript函数被调用时定义为this。您使用pipe作为回调,因此它的上下文变为window,因为它从window.requestAnimationFrame调用。

+0

这有效,但看看编辑。 –