我试图了解闭包但我没有得到如何访问不再存在的函数的变量。 所以我写了这个。
function foo() {
var from = 'from node';
function func() {
console.log('hello world', from);
}
func();
}
foo();
输出
node index.js
hello world from node
好的,这也有效
现在如果我将func移动到全局范围
function func() {
console.log('hello world', from);
}
function foo() {
var from = 'from node';
func();
}
foo();
它并没有像我想的那样奏效。 如果我绑定此然后调用该怎么办? 喜欢这个
function func() {
console.log('hello world', this.from);
}
function foo() {
var from = 'from node';
func.bind(this)();
}
foo();
据我所知,这应该可行,因为我明确地给了它这个变量。
但它仍然是未定义的打印,不明白为什么。