[英]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.