我正在逐步創建嵌套對象。原始代碼可以工作,但是簡化的代碼不會。Uglify打破逐步嵌套對象創建
工作原始代碼
function(type, id, fieldName) {
if (!this.model.proposed_changes)
this.model.proposed_changes = {};
if (!this.model.proposed_changes[type])
this.model.proposed_changes[type] = {};
if (!this.model.proposed_changes[type][id])
this.model.proposed_changes[type][id] = {};
if (fieldName) {
this.model.proposed_changes[type][id][fieldName] = this.model.proposed_changes[type][id][fieldName] || {};
}
}
變醜代碼(增加了可讀性換行)
function(e, i, n) {
this.model.proposed_changes || (this.model.proposed_changes = {}),
this.model.proposed_changes[e] || (this.model.proposed_changes[e] = {}),
this.model.proposed_changes[e][i] || (this.model.proposed_changes[e][i] = {}),
n && (this.model.proposed_changes[e][i][n] = this.model.proposed_changes[e][i][n] || {})
}
當this.model.proposed_changes
爲undefined
表示Cannot read property <ID passed in> of undefined
時,此錯誤的函數出錯。我不知道爲什麼醜化的代碼不起作用,但它似乎不是順序運行,即使它們應該是(https://msdn.microsoft.com/en-us/library/9b37css7(v=vs.94).aspx)
我使用gulp-uglify與其他配置其他比保持許可證的機智,但我已經試過這與mangle: false
沒有任何效果。
是否有某種方法可以強制uglify確保按順序進行分配?假設問題出在哪裏?
背景
在我的例子,我保證this.model存在,但並不表明它有一個叫做proposed_changes子對象。這種模式一直持續到我有這個.model.proposed_changes [type] [id] [fieldName]。如果有更好的方法來做到這一點,我一定會感興趣。
命令總是按順序在JS中執行。粗糙的代碼應該與原來的完全一樣。你有沒有嘗試用原來的uglified函數替換?它是否也會失敗?你說,'this.model'保證存在,但你真的檢查過嗎? – Thomas
你的建議幫助我找到了問題,所以謝謝!後端將this.model.proposed_changes錯誤地初始化爲「{}」而不是「{}」。 – SethBoyd