绑定后Javascript甚至无法访问变量

时间:2017-02-23 13:00:15

标签: javascript closures

我试图了解闭包但我没有得到如何访问不再存在的函数的变量。 所以我写了这个。

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();

据我所知,这应该可行,因为我明确地给了它这个变量。

但它仍然是未定义的打印,不明白为什么。

0 个答案:

没有答案