【发布时间】:2020-05-28 06:34:36
【问题描述】:
考虑以下代码:
var obj = {
name: 'Hans',
print: function(p) {
console.log(this.name)
}
};
obj.print(); // prints 'Hans'
我们知道print 函数在对象obj 上被调用。换句话说,obj 是print 的执行上下文(的一部分)。简单吧?
现在,这就是我正在努力理解的内容: 考虑将函数引用存储在数组中:
var funcs = [function(p) {
console.log(this.length, this)
}];
funcs[0](); // prints 1 which is the length of the array 'func' and also [ [Function] ]
表示数组运行时第一个元素的执行上下文就是数组本身!!我的假设是存储在数组中的只是对函数的引用,所以它相当于:
var f = function(p) {
console.log(this)
};
var funcs = [f];
f(); // prints Window
事实证明这是错误的。 我在这里错过了什么?
【问题讨论】:
-
prints undefined什么意思?funcs[0]()会做预期的事情 -
最后一个 sn-p 没有记录
undefined。它记录window对象。 -
@Barmar 刚刚完成编辑。谢谢。
标签: javascript arrays this executioncontext