我试图让以下代码正常运行,但没有任何运气,并且我看不到如何执行此操作的明确解决方案。
export default {
model: null,
set: function (data) {
this.model = data
},
account: {
update: function (data) {
this.model.account = data
}
}
}
我的问题是 account.update
失败,因为 this.model
不存在。我怀疑子对象获得了一个新的 this
,因此是我的问题,但我不知道如何修复它。
我在这里尝试了替代方案:
export default (function () {
let model = null
function set (data) {
this.model = data // I also tried without the `this.` but without any luck too
},
function updateAccount(data) {
this.model.account = data
}
return {
'model': model,
'set': set,
'account': {
'update': updateAccount
}
}
})()
但显然同样的规则适用。
也许值得注意的是,我正在使用 Babel 将 ES6 编译为 ES5 javascript。
最佳答案
它失败了,因为this
(在本例中)引用了窗口对象。像这样引用对象本身:
let myModel = {
model: null,
set: function (data) {
myModel.model = data // reference myModel instead of this
},
account: {
update: function (data) {
myModel.model.account = data // reference myModel instead of this
}
}
}
关于javascript - 在 Javascript 中对其进行父级处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36840665/