2

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!

3 Answers 3

3
this.init = function () {
    draw();
}

draw() should be this.draw() otherwise the function is called through the global window object.

Sign up to request clarification or add additional context in comments.

1 Comment

That was also one of the problems, but it's weird that Google Chrome showed problem in the line requestAnimationFrame(this.render);. Thank you for the pointer!
2

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();`
  };
}

2 Comments

@Ian, requestAnimationFrame(callback) is optimized for canvas animations.
@NullGeo I'm not sure what the point of that comment was. All I was saying was setTimeout is a good example of losing scope that people get tricked by
0

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);
}
}

2 Comments

Why are you posting an answer? Just click the check next to the one that solved your issue.
@sillylittleme, I posted the answer so that other users could see how I fixed it. I don't want others to have this issue: xkcd.com/979 :D Also, I marked one of them as answers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.