![](/img/trans.png)
[英]Javascript Module Pattern create multiple instances using Prototype
[英]Module/prototype and multiple instances
我試圖掌握“ OOP” JavaScript技術,並且今天開始編寫一個小型測試應用程序。 基本上,這是一個游戲循環,每次更新時都要增加坐標,以便移動HTML元素。
問題是我希望能夠運行應用程序的多個實例,因此,我試圖將實例數據存儲在this
,但保存在我的構造函數和exec()
方法是不是在私人可用update()
方法。 軍官似乎是什么問題?
var Jsloth = (function () {
var Jsloth = function () {
var sloth = document.createElement('div');
var attr = document.createAttribute('class');
attr.value = 'sloth';
sloth.setAttributeNode(attr);
this.sloth = document.getElementsByTagName('body')[0].appendChild(sloth);
};
var exec = function () {
this.x = 0;
this.y = 0;
var that = this;
setInterval(function () {
that.update();
}, 1000/10);
};
var update = function () {
this.x++;
this.y++;
this.sloth.style.left = this.x + 'px';
this.sloth.style.bottom = this.y + 'px';
};
Jsloth.prototype.constructor = Jsloth;
Jsloth.prototype.exec = exec;
Jsloth.prototype.update = update;
return Jsloth;
})();
var sloth1 = new Jsloth();
sloth1.exec();
編輯:更新了具有工作解決方案的代碼!
您尚未向原型添加update
。 該方法中this
的值很可能是window
對象。
從此更改您的呼叫:
update();
對此:
update.call(this);
或將update
添加到.prototype
:
Jsloth.prototype.update = update;
並使用:
this.update();
但是,如果要從setInterval()
調用update()
,則需要確保this
值正確。
為此,您可以傳遞一個匿名函數,並在變量中保留對外部this
值的引用。
var exec = function () {
this.x = 0;
this.y = 0;
var that = this;
setInterval(function() {
that.update();
//update.call(that); // if you didn't add update() to the .prototype
}, 1000/10);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.