JavaScript Magic Tricks: Fancy Assignment
Today, let's do a test to see how many different ways there are to write simple JavaScript assignment statements. Here are the test statements, only three lines:
var a=1;
a=2;
console.log(a);
For the assignment statement a = 2 in the second line, let's see how many different forms we can transform it into. The first variation is to write it inside an IIFE (Immediately Invoked Function Expression):
var a=1;
(function(){
a=2;
})();
console.log(a);
The second variation is to use eval to execute the assignment statement:
var a=1;
eval(a=2);
console.log(a);
These two variations are relatively basic and can be easily understood by beginning programmers. Now let's increase the difficulty a bit. The third variation is using evaluated assignment statement with transformations:
var a=1;
var b=["a","=",2];
eval(b[0]+b[1]+b[2]);
console.log(a);
But it seems that eval can only be played at this level. Let's show some more difficult variations next.
The fourth variation is to use constructor functions:
var a=1;
[].constructor.constructor(a=2);
console.log(a);
Or:
var a=1;
[].constructor.constructor(a=2)();
console.log(a);
The fifth change, the upgrade of constructor function:
var a=1;
var b=["a","=",2];
[].constructor.constructor(b[0]+b[1]+b[2])();
console.log(a);
As with the change in the content of eval, the code executed on the structure is also transformed using the splicing of array content:
The sixth variation, deformation of constructor function:
var a=1;
var b=["a","=",2,"constructor"];
[][b[3]][b[3]](b[0]+b[1]+b[2])();
console.log(a);
The seventh variation, obfuscation and encryption: Using JShaman JavaScript Obfuscator to obfuscate above code.
var a=0x2c0f8^0x2c0f9;
var b=['a','=',0xe3b2c^0xe3b2e,'constructor'];
[][b[0xa8ddf^0xa8ddc]][b[0xb3a35^0xb3a36]](b[0x3333f^0x3333f]+b[0x84d18^0x84d19]+b[0x50958^0x5095a])();
console['log'](a);
The resulting code completely obscures the assignment operation of a=2.
Top comments (0)