Cyril N. Cyril N. - 7 months ago 4
Javascript Question

Parenting this in Javascript

I'm trying to make the following code works without any luck, and I can't see a clear solution on how to do it.

export default {
model: null,
set: function (data) {
this.model = data
},
account: {
update: function (data) {
this.model.account = data
}
}
}


My issue here is that
account.update
fails because
this.model
does not exists. I suspect that the sub object gets a new
this
, hence my issue, but I don't know how to fix it.

I tried the alternative here :

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
}
}
})()


But apparently the same rule applies.

Maybe it's worth noting that I'm using Babel to compile ES6 down to ES5 javascript.

Answer

It fails because this refers (in this case) to the window object. Reference the object itself like 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
        }
    }
}
Comments