/*
* =========================================================
*
* JavaScript Lexical spoofing
*
* 1. Spoofing the lexical scope can cause performance degradation.
* 2. When the engine finds the eval () and the WITH () functions in the code, the engine does not know what code they will receive in the lexical phase, and the engine can simply assume that the identifiers are invalid.
* 3. When compiling the source code in JavaScript, one of the steps is to do a lot of optimization of the code, when encountering the above two functions, the engine can only do no code optimization, this is the reason to reduce performance.
* The 4.eval () and with () functions will function at run time.
*
* =========================================================
* */
function foo (str, a) {
eval (str); Deceptive morphology
Console.log (A, b); 1 3
// }
//
var B = 2;
//
Foo ("var b = 3;", 1);
//
var obj = {
A:1,
B:2,
C:3
// };
//
Console.log (OBJ.A);
Console.log (OBJ.B);
Console.log (OBJ.C);
With is often used as a shortcut to repeatedly reference multiple properties in the same object.
It is deprecated, however, because it alters the current scope, degrades performance, and can cause variable leaks.
Repeats the calling object itself without looping.
With (obj) {
A = 3;
b = 4;
c = 5;
// }
//
Console.log (OBJ.A);
Console.log (OBJ.B);
Console.log (OBJ.C);
With
First we know a = 2; is an assignment operation (LHS). When Foo passes in a reference (obj), with changes the
A property value in the reference scope, which acts as a scope lookup when the reference does not find a variable, and performs a lookup of the A variable to the upper-level scope
When a variable is not found in the reference scope, Foo scope, global scope, with automatically creates a global variable (if finding a variable in the scope above will change the value of the variable),
This is also known as a variable leak, which is caused by the assignment of the a=2 execution, and JavaScript automatically creates a global variable, depending on the attributes in JavaScript, when the variable declaration identifier is not seen before the assignment operation.
The precondition is that the above content will only be produced in the non-strict mode, and the WITH function will be completely banned in strict mode.
With is actually based on the object reference you pass to it, creating a completely new lexical scope from nowhere.
var a = 10; Here you can verify that with changed the value of the A variable. If this variable is not defined, Console.log (a); Print is also 2.
function foo (obj) {
With (obj) {
A = 2; Exactly equals assignment operation
// }
// }
var O1 = {A:3};
var O2 = {B:3};
Foo (O1);
Console.log (o1.a); 2
//
Foo (O2);
Console.log (o2.a); Undefined
Console.log (a); 2--is not good, a was leaked to the global scope!
JavaScript II, Eval, and with functions