Access local variable inside a callback function

前端 未结 4 1333
猫巷女王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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-08 02:35

    You could redefine the callback function in the current scope:

    var inner = function() { console.log(x); }
    
    (function(cb) { var x = 123; eval('cb = ' + cb.toString()); cb(); })(inner);
    
    // or
    
    (function(cb) { var x = 123; eval('(' + cb.toString() + ')')(); })(inner);
    

    This will not work if the function relies on anything in the scope in which it was originally defined or if the Javascript file has been minified. The use of eval may introduce security, performance, and code quality issues.

提交回复
热议问题