简体   繁体   中英

Javascript bind this to a function outside object

I have read about bind being used to access this inside a function outside the object but for some reasons I am not able to do that.

function test (len){
    return this.length - len;
}
var SETTINGS = {
     length : 21,
     trimmed: test.bind(this,5),
     x: function(){
        return this.length;
     }
};
SETTINGS.x(); // this is available.
SETTINGS.trimmed(); //len is 5 but this is Window.

May be it has something to do with my understanding of bind.

That happens because at the time you are binding this it points to window object. This is a little tricky, but in JS just because this is within an object it doesn't automatically become the object . It is more like: this points to the window unless some rule is applied .

What rule you might ask? From an amazing book series You Don't Know JS :

Determining this

Now, we can summarize the rules for determining this from a function call's call-site, in their order of precedence. Ask these questions in this order, and stop when the first rule applies.

Is the function called with new ( new binding )? If so, this is the newly constructed object.

var bar = new foo()

Is the function called with call or apply ( explicit binding ), even hidden inside a bind hard binding? If so, this is the explicitly specified object.

var bar = foo.call( obj2 )

Is the function called with a context ( implicit binding ), otherwise known as an owning or containing object? If so, this is that context object.

var bar = obj1.foo() - that is why SETTINGS.x(); works btw.

Otherwise, default the this ( default binding ). If in strict mode, pick undefined, otherwise pick the global object.

var bar = foo() - your case

In your case the default rule applies.

Be aware of an ES6 arrow functions , as they bind this (just like bind ) automatically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM