Reputation: 24659
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...
Upvotes: 0
Views: 59
Reputation: 33399
.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();
Upvotes: 2
Reputation: 77482
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.
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);
Upvotes: 3