Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject variable into function's scope

So, I want to do something like this:

    var a = 'a';

    var dummy = function() {

        // Print out var 'a', from the scope above
        console.log('Dummy a: ' + a);

        // Print out 'b', from the 'compelled' scope
        console.log('Dummy b: ' + b);
    }

    (function() {

        var b = 'otherscope';

        // I know apply won't work, I also don't want to merge scopes
        dummy.apply(this);

        // I want something like this:
        dummy.compel(this, [], {b: 'injected!'});

    })();

But that won't work.

I don't actually want a function to be able to reach 2 scopes, I DO want to be able to set the 'b' variable used inside the dummy function from the outside.

like image 928
skerit Avatar asked Mar 21 '13 19:03

skerit


People also ask

Is VAR globally scoped?

The var statement declares a function-scoped or globally-scoped variable, optionally initializing it to a value.

What is a function's scope?

Function scope: Variables that are declared inside a function are called local variables and in the function scope. Local variables are accessible anywhere inside the function. Block scope: Variable that is declared inside a specific block & can't be accessed outside of that block.

Why is var function scoped?

var is called as function scope that is if a variable is declared using var keyword it will be accessible throughout the function. let & const are also called as block scope that is they are accessible within that particular block.

Which kind of variables live in the local scope?

The scope of a variable is the region of your program in which it is defined. A global variable has global scope -- it is defined everywhere in your JavaScript code. On the other hand, variables declared within a function are defined only within the body of the function. They are local variables and have local scope.


1 Answers

You can make b a parameter for the function, or a global variable.

var a = 'a';
var dummy = function(b) {
   ...
}

or

var a = 'a';
var b;
var dummy = function() {
   ...
}

The first allows you to choose when the dummy function has access to the variable, the second allows it to be accessed everywhere.

like image 56
Ben McCormick Avatar answered Oct 05 '22 23:10

Ben McCormick