Accessing a local variable inside a callback function

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

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

// test 4
(function(cb) { cb.bind({x: 123})(); })(inner);

All tests result in: ReferenceError: x undefined

Does anyone know how to access "x" as a local variable inside a callback?

+8
source share
4 answers

Fact: when you do var inner = function() { console.log(x); }in your first line, xnot defined. What for? Because innerthere is no local x declaration inside your function (which would be done with var x = something). Then the runtime will look in the next area, that is, in the global area. There is also no declaration x, therefore xalso not defined there.

, x, 4 IIFE. IIFE x , . , , console.log() x, IIFE, .

, inner, . , , x ( ), x , inner. , x , , .

, , inner IIFE, x, inner, , x , , , x , . , .

, , console.log() inner, inner, :

var inner = function(x) { console.log(x); }
// test 1
(function(cb) { var x = 123; cb(x); })(inner);
+10

x :

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

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

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

JS , . , , JS , , .

+3

:

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

, - , , Javascript . eval , .

0

Have you tried to use events? Create an event inside an anonymous function, then subscribe to it in your own function somewhere else that executes your logic.

0
source

All Articles