我正在阅读一些关于 javascript 的文档,并偶然发现了以下代码示例:
var o = {
value: 1,
outer: function () {
var inner = function () {
console.log(this); //bound to global object
};
inner();
}
};
o.outer();
它输出window.
我无法弄清楚为什么关键字绑定到this全局对象 ( window) 而不是父对象 ( outer)。
如果outer要从inner' 范围内访问,则必须将outer' this(就像传递outer自身)inner作为参数传递给其本地函数。所以,正如预期的那样:
var o = {
value: 1,
outer: function () {
var inner = function (that) {
console.log(that); //bound to global object
};
inner(this);
}
};
o.outer();
输出outer。
在outer' 范围内绑定到对象this本身(即捆绑)?outerinnerouterthisouter
ECMAScript 规范指出,当进入函数代码的执行上下文时,如果 «caller provided thisArg» 为null或undefined ,则this绑定到全局对象。
但以下内容:
var o = {
outer: function () {
var inner = function () {
console.log('caller is ' + arguments.callee.caller);
};
inner();
}
}
输出对象outer本身:
caller is function () {
var inner = function () {
console.log('caller is ' + arguments.callee.caller);
};
inner();
}
另一方面,但可能相关,请注意:
在严格模式下,第一个代码段输出undefined而不是 window。