功能未显示正确的结果

时间:2016-01-27 03:04:15

标签: javascript

我写了这段代码

var foo = {
    x:2,
    baz: {
        x:1,
        bar:function() {
            return this.x;
        }
    }
}

var go = foo.baz.bar;
console.log(go());

答案是不确定的。但为什么? 当go映射到函数bar时,它应该返回2,因为x:2中有foo

1 个答案:

答案 0 :(得分:0)

回答这个问题,正如图沙尔在评论中所说:

  

上下文取决于函数的调用方式

以下是使用bindcallapply

来说明实现目标的方法的片段

var foo ={
  x:2,
  baz: {
    x:1,
    bar:function() {
      
      return this.x;
    }
  }
};

var go = foo.baz.bar;
console.log("go(): " + go()); //this === window, window.x is undefined
console.log("go.bind(foo)(): " +go.bind(foo)()); //this === foo, foo.x is 2
console.log("go.bind(foo.baz)(): " +go.bind(foo.baz)()); //this === foo.baz, foo.baz.x is 1

console.log("go.apply(foo): " + go.apply(foo)); //2
console.log("go.apply(foo.baz): " + go.apply(foo.baz)); //1

console.log("go.call(foo): " + go.call(foo)); //2
console.log("go.call(foo.baz): " + go.call(foo.baz)); //1

var x = 100;
console.log(go()); //100, since window.x == 100