I am doing some excercise, and I have issue with losing "this" context in a pipe method:
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: that cause "this is undefined, so it has no render function"
Ad.2: if above commented, still "this" context is undefined so pipe is not a function
initialization:
function init () {
var m = new Main();
requestAnimationFrame(m.pipe);
}
window.onload = function () {
init();
}
full object code:
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();
}
the renderGroup is plain forEach.
What causes the context lost?