简体   繁体   English

在对象内部调用JS函数

[英]Call JS Function inside an Object

I am new to OO in JavaScript and trying to make this simple canvas demo: 我不熟悉JavaScript的OO,并尝试制作此简单的canvas演示:

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. 我想要做的是渲染SolarSystem ,我想调用其内部的render()。 I cannot call render() from render(), how can I do that without getting Uncaught TypeError: Type error in the console? 我无法从render()调用render(),如何做到这一点而又不会出现Uncaught TypeError: Type error在控制台中Uncaught TypeError: Type error Thanks! 谢谢!

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

draw() should be this.draw() otherwise the function is called through the global window object. draw()应该是this.draw()否则通过全局window对象调用该函数。

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. 因为this会根据您所使用的范围而变化,所以self可以很容易地引用原始对象。 Then, when you need something off the SolarSystem() object, you can reference it using self.method() . 然后,当需要SolarSystem()对象以外的对象时,可以使用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. 您可能不会在示例中看到好处,但是如果/当您开始将范围应用于方法时,将会看到它的用处。 eg 例如

function MyObject(){
  var self = this;

  var private = function(){
  };
  this.Public = function(){
    // try it at home:
    // call      `self.private();`
    // then call `this.private();`
  };
}

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. 好的,正如布拉德·克里斯蒂(Brad Christie)所说,我指的是该功能的局部范围,而不是对象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);
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM