Access javascript variables from a call zone

I am trying to define a function that can access variables that are in the scope of the function that calls it.

(I'm trying to create a string formatter that is prettier than "a" + b, and shorter than String.format ("a {0}", b). So I can get SF ("a {b}" ), and I do not know if this is possible)

So

function magic (str) {
    return parentScope [str]; // or return eval (str);
    // or something like that
}

function call () {
    var a = 1;
    alert (magic ("a"));
}
call ();

will warn "1".

I can currently do this if the function return code should be evaluated, but it seems like there should be a better way.

+3
3

"" :

function call() {
    function magic(str) {
        return a; 
    }

    var a = 1;
    alert( magic() );
}
call();

. AJAX, - .

UPDATE

. , , JavaScript, .

2

. , , .

String.prototype.arg = function()
{
    result = this;

    // This depends on mootools, a normal for loop would do the job, too  
    $A(arguments).each((function(arg) 
    {
        result = result.replace("%", arg);
    }).bind(this));

    return result;
}

:

"%-% %".arg(1,2).arg(3)

"1-2 3"
+2

, javascript. yes, .

- (apply, call, other), : , , string.format, er....

0

@sebasgo is correct, you cannot do exactly what you are trying to do. But I thought you might like the Prototype String.interpolate method :

"#{animals} on a #{transport}".interpolate({ animals: "Pigs", transport: "Surfboard" });
//-> "Pigs on a Surfboard"

var syntax = /(^|.|\r|\n)(\<%=\s*(\w+)\s*%\>)/; //matches symbols like '<%= field %>'
var html = '<div>Name: <b><%= name %></b>, Age: <b><%=age%></b></div>';
html.interpolate({ name: 'John Smith', age: 26 }, syntax);
// -> <div>Name: <b>John Smith</b>, Age: <b>26</b></div>
0
source

Source: https://habr.com/ru/post/1714253/


All Articles