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

后端 未结 4 965
无人共我
无人共我 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:22

    Partial Application

    You can do partial application:

    // This lets us call the slice method as a function
    // on an array-like object.
    var slice = Function.prototype.call.bind(Array.prototype.slice);
    
    function partial(f/*, ...args */) {
    
        if (typeof f != 'function')
            throw new TypeError('Function expected');
    
        var args = slice(arguments, 1);
    
        return function(/* ...moreArgs */) {
            return f.apply(this, args.concat(slice(arguments)));
        };
    
    }
    

    What Object is this Function Bound To?

    Additionally, there's a pretty straight-forward solution to the first part of your question. Not sure if this is an option for you, but you can pretty easily monkey-patch things in JS. Monkey-patching bind is totally possible.

    var _bind = Function.prototype.apply.bind(Function.prototype.bind);
    Object.defineProperty(Function.prototype, 'bind', {
        value: function(obj) {
            var boundFunction = _bind(this, arguments);
            boundFunction.boundObject = obj;
            return boundFunction;
        }
    });
    

    Just run that before any other scripts get run, and any script which uses bind, it will automatically add a boundObject property to the function:

    function f() { }
    var o = { };
    var g = f.bind(o);
    g.boundObject === o; // true
    

    (Note: I'm assuming you're in an ES5 environment above due to the fact that you're using bind.)

提交回复
热议问题