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!
