reader reader - 1 month ago 4
Javascript Question

Javscript bind working with its instance

Lets take an object

var o = {a : 10 ,b:20,f:function(){ return this.a + this.b; }};
console.log(o.f())//30 works as expected


var o = {a:10,b:20,f:function(){ return this.a + this.b; }};
var p = o;
p.a = 1;
p.b = 4;
console.log(p.f()); // 5 works fine
console.log(o.f()); //5,it should 30 right but why it is showing 5

why is it working like this. If i do
it should get the value from object

It looks like i have not understood the bind properly

console.log(o.f.bind(o)())//gives 5
console.log(o.f.bind(this)())//gives 30

please give the difference between these two lines codes.


You are assigning an object reference to another one variable, not a copy.

var o = {a:10,b:20,f:function(){ return this.a + this.b; }};
var p = o; //Assigning the reference of o to p.

Hence it is behaving like that and this is how the language works.

When comes to your second question,

console.log(o.f.bind(o)()); // 5 

This doesn't have any effect at all. You are not at all changing the this value of that function.

But the second line of code,

console.log(o.f.bind(this)()); // NaN

Changes the this value of that function to the this value of the context where the bind is being executed. For example, If you are executing it from window's context, this would be window, window.a will be undefined and window.b will also be undefined. So undefined + undefined will return NaN. Not 30 as you are saying.