What object javascript function is bound to (what is its “this”)?

后端 未结 4 967
无人共我
无人共我 2020-12-01 21:04

I know that inside the function it is this.

var func = function {
    return this.f === arguments.callee; 
    // => true, if bound to some o         


        
4条回答
  •  忘掉有多难
    2020-12-01 21:16

    A function in javascript is not technically bound to anything. It may be declared as a property of an object as in:

    var obj = {
        fn: function() {}
    }
    obj.fn();
    

    But, if you get the function into it's own variable by itself, it is not bound to any particular object.

    For example, if you did this:

    var obj = {
        fn: function() {}
    }
    var func = obj.fn;
    func();
    

    Then, when you call func() which in turn executes the fn() function, it will have no association with obj at all when it is called. Associating an object with a function is done by the caller of the function. It is not a property of the function.

    If one were to use fn.bind(obj), that creates a new function that just internally executes a call to obj.fn(). It doesn't magically add any new capabilities to javascript. In fact, you can see a polyfill for .bind() to see how it works here on MDN.


    If you are expecting this to always be a particular object no matter how a function is called, that is not how javascript works. Unless a function is actually a shim that forces an association with a hard-wird object when it's called (what .bind() does), then a function doesn't have a hard-wired association. The association is done by the caller based on how it calls the function. This is different than some other languages. For example, in C++, you can't call a function without having the right object to associate with it at call time. The language simply won't resolve the function call and you get a compile error.

    If you are branching on types in javascript, then you are probably not using the object-oriented capabilities of the language properly or to your best advantage.

提交回复
热议问题