Function Arguments Passing and Return

前端 未结 4 1913
无人及你
无人及你 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:28

    the code won't work because inside the anonymous function you lose the reference to this.baz of foo object when used in another context

    you can use the apply() method to redefine the context, like so

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

    and this returns correctly 1 because apply() method change the execution context to the object passed as argument

    typeof arguments[0].apply(foo);
    

    returns numberas expected

提交回复
热议问题