2

In the below binding snippet:

function foo(something) {
    this.a = something;
}

var obj1 = {};

var bar = foo.bind( obj1 );
bar( 2 );
console.log( obj1.a ); // 2

var baz = new bar( 5 );
console.log( obj1.a ); // 2
console.log( baz.a ); // 5

In this step var bar = foo.bind( obj1 ); we are binding obj1 which is empty to the foo function .

After executing bar(2) , obj1 value 2 .

Want to know what bar(2) had triggered?

My Assumption:

Since bar is assigned to foo and binded with obj1 , invoking bar(2) could have assigned the this.a = 2 and kept that value in obj1(i.e.obj1 = { a: 2 }).

Is my assumption right?

4 Answers 4

2

Here bind(obj1) works like you are overriding default scope of foo function to obj1 ,so this keyword replaced with blank object (obj1) inside foo.

function foo(something) {
    //this = {}  (obj1);
    //this.a == obj.a
    this.a = something;
}

var obj1 = {};

var bar = foo.bind(obj1);
Sign up to request clarification or add additional context in comments.

Comments

2

Calling bind() on a function returns a new bound function. When you call this bound function, it will execute the original function with the context you passed in as the first argument. Therefore this inside foo points to obj1 when you call it through the bound function.

Comments

2

To understand this , You need to first take what .bind does?

bind is function which returns another function which is called bound.

function x (){
  console.log(this.item)
}

consider the above code , does not have any idea about what item is.

var obj = { item  : 10};

consider this object , this object does know about its item property.

When you call .bind on x object(the function) , it returns the same copy of function(called bound) , but with the context of obj {item: 10}.

var bound = x.bind(obj);

This particular statement says , give this particular function with the context of obj.

Now if we call bound() it will print 10

Comments

0

Your assumption is right.

 var bar = foo.bind( obj1 );

makes bar a reference to the foo object. Thus, you can now access the function via bar.

 bar( 12 );

prints 12 if you call console.log() and so on.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.