0

I was surprised about the behavior of the following script, when executed in Chrome's js console:

var me = { name: 'John'};

function theFunc(){
 console.log(this);
}

theFunc.bind(me);

theFunc();//this is window???

I was expecting the bind function call to bind to the object literal...

2 Answers 2

3

You need call (assign it to variable) function like this

theFunc = theFunc.bind(me);

theFunc();

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

.bind

Example

P.S. In our case you also can use call or apply, like this

var me = { name: 'John'};

function theFunc(){
 console.log(this);
}

// theFunc.call(me); or

theFunc.apply(me);

Example

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot Alexander! +1
​+1 for mentioning call and apply.
2

.bind() returns a new function, that must then be set to a variable to be saved.

See MDN.

var me = { name: 'John'};

function theFunc(){
 console.log(this);
}

theFunc = theFunc.bind(me);

theFunc();

1 Comment

Mine uses a Stack Snippet. ;)

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.