【问题标题】:Is there any possible way to access this variable from callback?有没有办法从回调中访问这个变量?
【发布时间】:2020-03-27 16:03:24
【问题描述】:

如何通过回调测试访问土豆,土豆匿名函数不能修改?绑定之类的都不行,有大佬有办法吗?

//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】:

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

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

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 2017-02-13
    • 1970-01-01
    • 2023-02-21
    • 1970-01-01
    • 1970-01-01
    • 2014-09-03
    • 1970-01-01
    相关资源
    最近更新 更多