簡體   English   中英

如何將構造函數對象值設置為其他值的函數?

[英]How can I set a constructor object value to be a function of other values?

我試圖通過在對象構造函數內的其他兩個屬性上運行函數來生成對象屬性。

當我運行以下代碼時:

var ConstObj = function() {
    this.compositionDict = {
        "rock": 0.8,
        "iron": 0.15,
        "gold": 0.05
    };
    this.totalVolume = 10000;
    this.compVolDict = Object.keys(this.compositionDict).reduce(function(prev, curr) {
        prev[curr] = this.compositionDict[curr] * this.totalVol;
        return prev;
    }, {});
}
var tempObj = new ConstObj;

我收到以下錯誤:

Uncaught TypeError: Cannot read property 'rock' of undefined(…)

我認為這是行不通的,因為在運行函數時實際上並未定義對象屬性-但是我不知道要執行的操作的良好解決方法。

我可以創建一個在創建對象后添加新屬性的函數,但似乎這種事情應該起作用。

這是一個問題this不是你的內部正確的值reduce功能。 每當創建新的閉包(例如function() { ... } ,都會創建一個新的上下文。 為了使this指向正確的上下文,您必須bind函數,或者必須使用變量來引用原始上下文。

this.compVolDict = Object.keys(this.compositionDict).reduce(function(prev, curr) {
    prev[curr] = this.compositionDict[curr] * this.totalVol;
    return prev;
}.bind(this), {});

或者,您可以使用變量來記錄要在函數內部使用的上下文。 這有點丑陋,但是您會在各種用戶態腳本中看到這種情況。

var _this = this;
this.compVolDict = Object.keys(this.compositionDict).reduce(function(prev, curr) {
    prev[curr] = _this.compositionDict[curr] * _this.totalVol;
    return prev;
}, {});

最后,另一種解決方案是使用ES6箭頭函數 顯然,這是最優雅的解決方案。

this.compVolDict = Object.keys(this.compositionDict).reduce((prev, curr) => {
    prev[curr] = this.compositionDict[curr] * this.totalVol;
    return prev;
}, {});

如果無法使用ES6,則可以使用諸如babel.js之類的編譯器 ,它將ES6轉換為ES5。 這是開始利用ES6的新功能,但仍然能夠在ES5環境中運行的好方法。

this.compositionDictundefinedreduce ,因為你在不同的范圍是。
function(prev, curr) {那個)

保存對ConstObj函數范圍的引用,然后使用該引用代替:

var ConstObj = function() {
    var that = this; // Store the reference to `this`.
    this.compositionDict = {
        "rock": 0.8,
        "iron": 0.15,
        "gold": 0.05
    };
    this.totalVolume = 10000;
    this.compVolDict = Object.keys(this.compositionDict).reduce(function(prev, curr) {
        prev[curr] = that.compositionDict[curr] * that.totalVol;
        return prev; // ^ use `that` instead of `this`
    }, {});
}

暫無
暫無

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

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