I am new to javascript and I am trying to implement a complicated data structure which requires modification of scope inside various functions. Then, I came across function.prototype.bind(). At first, I thought it was very useful. But, some of the results are unexpected. So, I wrote a demo code for testing and here is the code.
(function () {
this.t = 9.8765432
this.a = (function(){
this.t = 3.14159
this.b = (function(){return this.t;}).bind(this)
this.c = (function(){
this.t=1.23456
this.d=(function(){return t;}).bind(this)
return this
})()
return this
})()
console.log(this.a.b()) //My guess was 3.14159, at the end it is 1.23456
console.log((this.a.b.bind(this))()) //My guess was 9.8765432, at the end it is 1.23456
console.log(this.a.c.d()) //My guess was 1.23456, at the end it is 1.23456
console.log((this.a.c.d.bind(this))()) //My guess was 9.8765432, at the end it is 1.23456
return this
})();
Sadly, I guessed all the results incorrectly. This indicates I don't have enough understanding of this function. Can anyone explain it to me?
thiscontext of a function invocation which is not on an object (e.g.(function() { ... })()isundefined.