Javascript 在对象内调用JS函数
我不熟悉JavaScript中的OO,并尝试制作这个简单的画布演示:Javascript 在对象内调用JS函数,javascript,Javascript,我不熟悉JavaScript中的OO,并尝试制作这个简单的画布演示: 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
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(),如果不在控制台中获取uncaughttypeerror:Type error
,我如何才能做到这一点?谢谢 通常在对象中使用的是这条小线:
var self = this;
由于此
会根据您所处的范围而变化,self
使引用原始对象变得非常容易。然后,当您需要从SolarSystem()
对象中删除某些内容时,可以使用self.method()
引用它
您可能看不到示例中的好处,但如果/当您开始将作用域应用于方法时,您将看到它是多么有用。e、 g
function MyObject(){
var self = this;
var private = function(){
};
this.Public = function(){
// try it at home:
// call `self.private();`
// then call `this.private();`
};
}
draw()
应该是this.draw()
否则该函数是通过全局窗口
对象调用的。好的,正如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);
}
}
这也是问题之一,但谷歌浏览器在
requestAnimationFrame(this.render)一行中显示了问题,这很奇怪代码>。谢谢你的指点!你为什么要发布答案?只需单击解决您问题的复选框旁边的复选框。@sillylittleme,我发布了答案,以便其他用户可以看到我是如何解决的。我不希望其他人有此问题::D另外,我将其中一个标记为答案。@Ian,requestAnimationFrame(回调)针对画布动画进行了优化。@NullGeo我不确定该注释的意义是什么。我想说的是,setTimeout
是一个很好的例子,说明人们会被欺骗,从而失去作用域
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);
}
}