Reputation: 2585
I am new to OO in JavaScript and trying to make this simple canvas demo:
var c; // typeof c is the canvas element
function SolarSystem(plane, sun) {
this.plane = plane; // typeof plane is Canvas Ctxt
this.sun = sun;
this.init = function () {
draw();
}
this.render = function () {
c.height = c.height;
requestAnimationFrame(this.render);
this.draw();
}
this.draw = function () {
console.log(1);
}
}
What I want to do is, to render SolarSystem
, I want to call render() that is inside of it. I cannot call render() from render(), how can I do that without getting Uncaught TypeError: Type error
in the console? Thanks!
Upvotes: 2
Views: 105
Reputation: 101594
typically what's used in objects is this little line:
var self = this;
because this
changes depending on the scope you're in, self
makes it very easy to reference the original object. Then, when you need something off the SolarSystem()
object, you can reference it using self.method()
.
You may not see the benefits in your example, but if/when you began applying scope to your methods you'll see how it's useful. e.g.
function MyObject(){
var self = this;
var private = function(){
};
this.Public = function(){
// try it at home:
// call `self.private();`
// then call `this.private();`
};
}
Upvotes: 2
Reputation: 2585
Okay, as told by said by Brad Christie I was referring to the local scope of the function by saying this and not the object SolarSystem. The following worked perfect. Thanks again!
function SolarSystem(plane, sun){
this.plane = plane;
this.sun = sun;
var self = this;
this.init = function(){
self.draw();
}
this.render = function(){
c.height = c.height; // reset canvas
requestAnimationFrame(self.render);
self.draw();
}
this.draw = function(){
console.log(1);
}
}
Upvotes: 0
Reputation: 96790
this.init = function () {
draw();
}
draw()
should be this.draw()
otherwise the function is called through the global window
object.
Upvotes: 3