JavaScript Visibility Interaction

Given the following javascript snippet in scope:

var x = 10;

function sayx() {
  alert(x);
}

sayx();

Of course, you expect the message β€œ10” to appear in the message window, you can perform multiple nesting functions to interact with the way β€œx” is defined, because when you allow x to be an environment, a chain of areas approaches.

You can even run the β€œrecompile” level with eval to enter new areas at runtime. For example:

var x = 10;

function sayx() {
  alert(x);
}

function wrap(f) {
  return eval('(function() { var x = 20;(' + f + ')(); })');
}

wrap(sayx)();

, toString, . , , , x.. "20", "10".

, , , 'f' . , , .

, , ? - :

function withScope(f, scope) { ??? }

---

var x = 10, y = 10;

function dothemath() {
  alert(x + y);
}

var haxthemath = withScope(dothemath, { x: 9000 });
haxthemath(); // 9010 not 20

, "", , , , , ( ), , .

, .

.


, , , "withScope", :

Window - window properties
Object - { var x = 10 }
Object - { var y = 5 + x }

, + , , :

withScope(somefunc, { foo: 'bar' })

Window - window properties
Object - { var x = 10 }
Object - { var y = 5 + x }
Ext scope - { foo = 'bar' }

, .

+3
4

/ , , .

this, functionName.call(scope, arg1,...) functionName.apply(scope, [arg1,...]); , , - - , . , ..

+4

, , , , - "".

, , , ecmascript 6

, , , - -, javascript . , , javascript, Java apis Javascript . steve yegge , . javascript - javascript, javascript! !

, , javascript, javascript, , .

0

, javascript, toString ?

function withScope(f, scope) {
    var toExec = "";
    for (var prop in scope) {
        toExec += "var " + prop + " = scope['" + prop + "'];"
    }
    toExec += "f = (" + f.toString() + ")";
    eval(toExec);
    return f;
}
var x = 10;
var f = function() {
    console.log(x);
};
withScope(f, {x: 20})();

, ...

0

, let, Javascript 1.7. Firefox let.

0

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


All Articles