Access local variable inside a callback function

前端 未结 4 1399
猫巷女王i
猫巷女王i 2021-02-08 01:37
var inner = function() { console.log(x); }

// test 1
(function(cb) { var x = 123; cb(); })(inner);

// test 2
(function(cb) { var x = 123; cb.apply(this); })(inner);

/         


        
4条回答
  •  鱼传尺愫
    2021-02-08 02:17

    The only way to access the local variable x in the callback, is to pass it as an argument:

    var inner = function(some_var) { console.log(some_var); }; //logs 123
    (function(cb) { var x = 123; cb(x); })(inner);
    

    OR

    var inner = function(some_var) { console.log(some_var); }; //logs 123
    (function(cb) { var x = 123; cb.apply(this,[x]); })(inner);
    

    OR

    var inner = function(some_var) { console.log(some_var); }; //logs 123
    (function(cb) { var x = 123; cb.call(this,x); })(inner);
    

    FURTHER

    Because JS is lexically scoped, trying to reference the local variable after the anonymous function has finished executing is impossible by any other means. If you don't pass it as an argument to make it available elsewhere, JS will see it as non-reachable and it will be eligible for garbage collection.

提交回复
热议问题