Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obfuscate javascript properties?

I've recently tested UglifyJS and YUI Compressor and noticed something odd.
Both minifiers don't seem to change the names of object properties, only the names of variables and functions.

for instance if I have the following code:

var objName = {first:2, second:4};
alert(objName.first + " " + objName.second);

the names first and second remain unchanged in the minified version.
Why is that?

like image 326
shoosh Avatar asked Feb 22 '11 17:02

shoosh


People also ask

Can you obfuscate JavaScript?

JavaScript obfuscation is a series of code transformations that turn plain, easy-to-read JS code into a modified version that is extremely hard to understand and reverse-engineer. Unlike encryption, where you must supply a password used for decryption, there's no decryption key in JavaScript obfuscation.

Is obfuscated JavaScript slower?

It certainly does slow down the browser more significantly on older browsers (specifically when initializing), but it definitely slows it down even afterwards.

How do I obfuscate a JavaScript file?

Press F12 to open Developer Tools inside Chrome. Now switch to the Scripts tab, right-click and choose De-obfuscate source. That's it! Alternatively, go to jsbeautifier.org and copy-paste the cryptic JavaScript /HTML code that you are trying to understand.

Does obfuscation affect performance JavaScript?

Name obfuscation does not affect the performance and should always be used. You can virtualize methods that are not computationally intensive.


2 Answers

Since in javascript a new scope is created in a function, you can scope your code in an immediately invoked function.

   // scoped
(function() {
    var objName = {first:2, second:4};
    alert(objName.first + " " + objName.second);
})();

Then using Google's Closure Compiler, if you turn on the "Advanced" optimization it will see that the properties are only used locally, and will obfuscate them.

   // result
var a={a:2,b:4};alert(a.a+" "+a.b);
like image 174
user113716 Avatar answered Sep 29 '22 12:09

user113716


It's because it doesn't know where the object is going to be used. It could be used externally by other code and you wouldn't want your other code to have to change whenever you obfuscate it.

Edit So basically, it's like that to prevent obfuscation from breaking external/internal references to properties that may not be possible to figure out while obfuscating.

like image 44
Richard Marskell - Drackir Avatar answered Sep 29 '22 12:09

Richard Marskell - Drackir