繁体   English   中英

在对象内部调用JS函数

[英]Call JS Function inside an Object

我不熟悉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);
    }

}

我想要做的是渲染SolarSystem ,我想调用其内部的render()。 我无法从render()调用render(),如何做到这一点而又不会出现Uncaught TypeError: Type error在控制台中Uncaught TypeError: Type error 谢谢!

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

draw()应该是this.draw()否则通过全局window对象调用该函数。

通常,对象中使用的是以下这一行:

var self = this;

因为this会根据您所使用的范围而变化,所以self可以很容易地引用原始对象。 然后,当需要SolarSystem()对象以外的对象时,可以使用self.method()引用它。

您可能不会在示例中看到好处,但是如果/当您开始将范围应用于方法时,将会看到它的用处。 例如

function MyObject(){
  var self = this;

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

好的,正如布拉德·克里斯蒂(Brad Christie)所说,我指的是该功能的局部范围,而不是对象SolarSystem。 以下工作完美。 再次感谢!

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