簡體   English   中英

模塊/原型和多個實例

[英]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();

編輯:更新了具有工作解決方案的代碼!

在JavaScript中, this (幾乎)完全取決於您如何調用函數,而不是由函數的定義位置/方式決定的。

你打電話的方式update

update();

... this將是全局對象(瀏覽器上的window ),如果使用"use strict"undefined

要設置thisupdate ,使用callapply

update.call(this);
// or
update.apply(this);

更多(在我的博客上)

您尚未向原型添加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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM