JavaScript examples from this post.


In [1]:
let dog = {
    sound: "woof",
    talk: function(){
        console.log([
            'output: ',
            this.sound
        ].join(''));
        console.log([
            'this: ',
            this
        ].join(''));
    }
}
dog.talk()


output: woof
this: [object Object]

In [2]:
var talkFunction = dog.talk
talkFunction()


output: 
this: [object global]

In [3]:
console.log(this)


[object global]

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


output: 
this: [object global]

Explanation of how 'dog.talk' loses its connection to 'dog'.

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


output: woof
this: [object Object]

'this' has changed from [object global] to [object Object] which is context 'dog'