簡體   English   中英

將屬性添加到JavaScript中的函數中的對象?

[英]Add property to object inside function in JavaScript?

可以通過任何方法在此函數(用作類)中向該對象添加另一個屬性:

function DP() {
    var _this = this;

    this.displayTypes = {
        normal: function(div) { _this.displayNormal(div) },
        round: function(div) { _this.displayRound(div) }
    }

    this.displayNormal = function(div) { ... };
    this.displayRound = function(div) { ... };

    this.display = function(div, type) {
        this.displayTypes[type](div);
    }
}

var dp = new DP();

// Now here I'd basically like to add another property to the DP.displayTypes
// called "rect" referencing to a function in a different class called
// DPExtension.displayRect(). So something like this:
//     rect: function(div) { DPExtension.displayRect(div) }

這樣我就可以調用dp.display("place-to-display", "rect") ,然后基本上從DPExtension類/函數執行displayRect("place-to-display") ,同時調用類似dp.display("place-to-display", "round") displayRound("place-to-display")將從DP執行displayRound("place-to-display")

怎么做到的? 我試圖用prototype做一些事情,但無濟於事...

由於似乎您希望所有DP實例共享對displayTypes更改,因此應使它由所有實例共享,而不是特定於實例。 您可以通過將其設置為DP的靜態屬性來實現:

function DP() {
    // these should probably go on DP.prototype as well
    this.displayNormal = function(div) { ... };
    this.displayRound = function(div) { ... };
}

// static
DP.displayTypes = {
    normal: function(div) { this.displayNormal(div) },
    round: function(div) { this.displayRound(div) }
};

DP.prototype.display = function(div, type) {
    this.displayTypes[type].call(this, div);
};

DP.prototype.displayTypes = DB.displayTypes;


// somewhere else
DP.displayTypes.rect =  DPExtension.displayRect;

您不必全部創建靜態屬性,可以直接在原型上定義displayTypes ,但是通過DB.displayTypes.foo = ...擴展比使用DB.prototype.displayTypes.foo = ...更好DB.prototype.displayTypes.foo = ...

您是否嘗試過像這樣添加它:

var dp = new DP();
dp.displayTypes['rect'] = function(div) { DPExtension.displayRect(div); };

我認為您可以在創建DP並傳遞其當前實例時將DP更改為具有顯示類型的對象。 創建顯示類型時的DP。

將DP的方法放在DP.prototype上。 以及稍后在DisplayTypes.prototype添加方法上使用DisplayTypes的方法將影響所有實例,將來的實例和已經創建的實例。

關於原型: https : //stackoverflow.com/a/16063711/1641941

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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