Function Arguments Passing and Return

前端 未结 4 1912
无人及你
无人及你 2021-01-25 06:37
  var foo = {
    bar: function() { return this.baz; },
    baz: 1
  };
  (function(){
    return typeof arguments[0]();
  })(foo.bar);

Why does this c

4条回答
  •  失恋的感觉
    2021-01-25 07:10

    To understand why this is not a reference to the object on which the function resides, you have to understand that JavaScript doesn't have classes. It has functions.

    In JavaScript, functions are never strictly "bound" to objects like they are in classful languages like Java, C#, whatever. A javascript function is just another type, like string and number, which means that you can pass functions around in variables like any other type. In your example, the function contained in foo.bar isn't aware of foo at all. It's just a function, minding its own business.

    So what does the this keyword do? It points to the execution context. In your example, you call the function inside foo.bar from the global scope (i.e. window), so that's what it points to. You can use apply() to call the function in the correct scope, but for that you would need access to that scope (in this case, the foo object). This negates any of the security advantages of passing along just the function, without the object.

    To "fix" this "problem", ECMAScript 5 (the future version of JavaScript) introduces bind(). This handy function lets you bind a function to a certain execution scope before passing it to another function, like this:

    var foo = {
        bar: function() { return this.baz; },
        baz: 1
    };
    
    var callback = foo.bar.bind(foo);
    
    (function(){
        return typeof arguments[0]();
    }(callback));
    

提交回复
热议问题