是否可以通过回调方法访问此变量?

问题描述 投票:0回答:1

如何通过回调测试访问potatos,不能修改potatos匿名功能?绑定等等不起作用,有人知道吗?

//This cannot be changed
!function(a){
    //
    let potatos = {
        count: 999
    }
    //
    let garden = {
        /**
         * 
         */
        callbacks: [],
        /**
         * 
         */
        showInfo: function() {
            this.callbacks.forEach((cb) => {
                cb();
            })
        } 
    }
    //
    global.garden = garden;//or window.garden
}();
/**
 * 
 */
function test() {
    console.log(potatos);//Error
}

garden.callbacks.push(test);
garden.showInfo();
javascript callback scope
1个回答
0
投票

没有JavaScript使用lexical scope作为变量。

test被声明为存在potatoes的任何范围之外。它无法访问该变量。

© www.soinside.com 2019 - 2024. All rights reserved.