Misa Ogura
Aug 25, 2017 · 1 min read

Hey Embre,

Thank you for your question, and yeah this one is quite counter-intuitive.

We’re interested in the value of this inside myFunc. If you focus on how myFunc is called inside myObj.myMethod, it is called on its own myFunc() without a parent object. Therefore in this case, this points to Window.

var myObj = {
myMethod: function () {
myFunc() // myFunc called on its own without a parent object
function myFunc () {
console.log(this)
}
}
}
myObj.myMethod()// Window { ... }

I agree that this should really belong to myObj. Unfortunately, this is the default behaviour in JavaScript.

As discussed in the article, there are ways to control the value of this in such scenarios. For example:

var myObj = {
myMethod: function () {
myFunc.call(myObj)

function myFunc () {
console.log(this)
}
}
}
myObj.myMethod()// { myMethod: f }

I hope this clears up your doubt!

)

    Misa Ogura

    Written by

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade