2016-05-15 65 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

這有效,但看看編輯。 –