我写了这段代码
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
。
答案 0 :(得分:0)
回答这个问题,正如图沙尔在评论中所说:
此上下文取决于函数的调用方式
以下是使用bind
,call
或apply
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