In [1]:
let dog = {
sound: "woof",
talk: function(){
console.log([
'output: ',
this.sound
].join(''));
console.log([
'this: ',
this
].join(''));
}
}
dog.talk()
In [2]:
var talkFunction = dog.talk
talkFunction()
In [3]:
console.log(this)
JS literally assigns the function named 'talk' from dog to talkFunction. 'this.sound' is undefined because 'this' points to [object global]. This is a somewhat analogous situation of calling an unbound method on a class in Python except that in Python error is raised because 'self' (analogous to 'this') is not passed into the function i.e. it is out of context. Example of Python raising that error.
In [4]:
var talkFunction = function(){
console.log([
'output: ',
this.sound
].join(''));
console.log([
'this: ',
this
].join(''));
}
talkFunction()
The act of assigning the function dog.talk
to a variable makes it a an "unbound" method. 'this' is not what is was before reassignment happened.
The 'bind' function fixes that.
In [5]:
let boundFunction = talkFunction.bind(dog)
boundFunction()