Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
Is there a recommended javascript code obfuscation tool?
I have searched it in stackoverflow,and someone suggest the 'YUI compressor'.
However it just do the following:
remove the annotatation/white space/new line
replace local variable
or something ele.
But It does not replace the property of one object.
Say I have a code like this:
var a=obj.fun();
var b=obj.pro;
I want something like this:
var xxx,yy,zz;
xxx=obj['yy']();
yy=obj['zz'];
Then even people re-format my code,he can not even know the propery/methods of one object unless he re-do the method/property replacement.
This is just an example, I just want the tool do more obfuscation other than just compress.
Any suggestion?
Try the Google Closure Compiler. In advanced mode it also refactors parts of your code and creates some performance improvements that way.
Javascript is a dynamically typed language, interacting with the browser, so it's almost impossible to do a proper analysis to find where an object can pop up in the code.
For these reasons you cannot safely rename the properties of an object.
You should try the google closure compiler, it provides three levels of writing:
The first one is WHITESPACE_ONLY
The second one is SIMPLE_OPTIMIZATIONS
The third one is ADVANCED_OPTIMIZATIONS
WHITESPACE_ONLY removes comments, trim line breaks and unnecessary spaces. The output code is identical to the source JavaScript.
SIMPLE_OPTIMIZATIONS also renames local variable and function parameters.
ADVANCED_OPTIMIZATIONS is the most aggresive, besides the optimization in the above two levels, it also does:
global variable renaming
remove uncalled functions
function inlining
For the give example:
//INPUT CODE
function unusedFunction(note) {
alert(note['text']);
}
function displayNoteTitle(note) {
alert(note['title']);
}
var flowerNote = {};
flowerNote['title'] = "Flowers";
displayNoteTitle(flowerNote);
WHITESPACE_ONLY result is :
//WHITESPACE_ONLY OUTPUT CODE
function unusedFunction(note){alert(note["text"])}function displayNoteTitle(note){alert(note["title"])}var flowerNote={};flowerNote["title"]="Flowers";displayNoteTitle(flowerNote);
SIMPLE_OPTIMIZATIONS result is:
//SIMPLE_OPTIMIZATIONS OUTPUT CODE
function unusedFunction(a){alert(a.text)}function displayNoteTitle(a){alert(a.title)}var flowerNote={title:"Flowers"};displayNoteTitle(flowerNote);
ADVANCED_OPTIMIZATIONS result is:
//ADVANCED_OPTIMIZATIONS OUTPUT CODE
alert("Flowers");
I think the SIMPLE_OPTIMIZATIONS and ADVANCED_OPTIMIZATIONS meet your need.
with my limited knowledge on this subject. I would like to suggest the google closure compiler:
http://code.google.com/closure/compiler/docs/api-tutorial3.html
It says there that they do property renaming
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am making a javascript library and wanted to make a custom variable syntax so instead of using var use $ like php. To be clear I DO NOT want to use PHP. I am making a special library for public use.
I honestly don't care if you give me a function I just really need to use $ instead of var please I really need this.
var x = 10; // Normal JavaScript variable
$x = 10; // Custom Variable Syntax which is what I would like
JavaScript provides no means to extend the language in this way.
If you want to invent your own syntax, you'll need to design your own programming language and transpile it to JavaScript (as CoffeeScript does, for example).
(NB: $x is a valid identifier in JavaScript, you just can't cause any variable name starting with a $ to be inferred (by JS) as being a locally scoped variable when you assign something to it. $x = 10; would therefore throw an error (or create a global if you weren't using strict mode)).
JavaScript Syntax is not customization and keywords can not be overloaded.
Language is language, you can't jump over it's rules. But you can look around, use it's native possibilities.
As I know- there is no option to write
$x = 10;
in javascript. Just no.
But you can dance like jQuery ($ as alias of window.jQuery- that's not solution, but just first think about similar actions).
Can you tell more about that problem? Why do you need that? Maybe there's simpler way?
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I'm a little confused on what to do here. I've seen a lot of people create modules in JS, but everyone usually does it differently. I've seen people wrap their WHOLE module in a (function(){})(); , or they declare an object literal, or do something crazy like window.Module = {};. I want to know what would be the best choice to be used (as in what you would think is most useful). Help would really be appreciated, and thanks.
There is only one official solution to create JavaScript modules. Anything else you have seen is either a polyfill for that solution, or a pale echo of the real thing.
The basic syntax is like so:
import otherStuff from "otherStuff.js";
var myThing = {};
myThing.stuff = function(){ /*...*/ };
myThing.do = function(){ otherStuff.doOther(); );
export default myThing;
It can get much more complicated, but the basics are:
Your module must be in a unique file. A file is a module.
Your module should probably export something, although this is not strictly necessary.
This is coming down the pipeline in JavaScript. Unfortunately, no one has been able to agree on the official specification of how to load the modules, so they are not on a track for any near-future release. That said, the specification is under development, and a polyfill that implements it has been created.
Your best bet to use the official module syntax is to run it through BabelJS and compile to a shim like Require (which uses the AMD format) so you can use it without the loader specification.
You can read more about the syntax here and here.
I would say : It depends on the final usage of your "module". If it's something that will be used internally, which means that no one else outside your business will use it, then anything can be used as long as you all agreed on the proper method. Otherwise, if it would be used by others : less global variables you create, better it is. As example, jQuery use "$" and "jQuery" as global variables (maybe others, but I'm not sure). When people adds modules to it, they always add them to window.jQuery.[Under jQuery var] where [Under jQuery var] shall be read on jQuery documentation for proper use.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I want to create a globally-accessible library myLib in Javascript. My library should do the following
Keep a somewhat persistent variable myLib.tax.
-- It should survive through the handling of a typical browser user event, at least in simple cases. I don't care if it survives longer than that or not.
-- external code should be able to set the value of this variable, either through a setter or otherwise.
Has a function myLib.applyTax(var price).
-- return value is price + myLib.tax.
-- I don't care what it does if either price or tax is not a number.
Lastly, a brief example of how to call this from another file, in such a way that:
-- for example, file A might set the value of the tax, then file B might apply the.
-- this works even though files A and B are unrelated.
The purpose of this question is for me to understand code and state encapsulation and how to use them from elsewhere.
EDIT: For the benefit of anyone seeing this later, what I did not understand when asking this question is that referring from javascript file A.js to javascript file B.js is a difficult problem unless that is enabled externally, for example in the html. For more detail, see How do I include a JavaScript file in another JavaScript file?
From your comments I see you would implement a Singleton Pattern in C# through static methods and data.
In Javascript you can do the same by managing the closures and putting that data into the outermost one, which would then be accessible to all code due to lexical scoping.
But I'd rather avoid singletons every day. Instead, use dependency injection as follows. This is just an example to show the technique, you'll have to code an actual solution yourself.
var lex = (function () {
var privatedata;
function privatemethod()
{
}
return {
publicmethod1: function (arg1, arg2) { ... },
publicmethod2: function (arg1, arg2) { ... },
getPublicData: function () { ... }
};
}());
This incapsulated object is then injected wherever you need it:
function consumerCode(lexicon)
{
...
}
consumerCode(lex); // injects the lex instance into the consumer code
By having only one instance and passing that same instance around wherever you need it, you will have pretty much what you were asking for.
This technique is not limited Javascript but also useful in C#. But in Javascript with loose typing it is especially powerful.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I heard from a JS developer recently that you should avoid using numbers inside function names.
For example:
function test1test() {
// function body
}
I've never come across this before so I was wondering if it's true? If so, why?
There's nothing wrong with having numbers in your function name, it's just a little unconventional. The ultimate goal in function and variable naming is readability and clarity of code, so if you think including a number in your function name make the code more clear, you should make that a priority.
However, for maximum readibility and clarity in most cases, your function names should be camelCase verb phrases to follow the predominant convention.
For instance, you might want to name a function convertToMp3(), in which case it would be silly to instead name the function convertToMpThree(). But you should avoid using names like obj2Array() or format2(), because those don't make your code more clear.
Ok, I'm going to try to answer this in without a my-opinion base...
Refering to W3's article on Javascript's best practices, we find the following statement, regarding to names:
good variable and function names should be easy to understand and tell you what is going on — not more and not less. One trap to avoid is marrying values and functionality in names. A function called isLegalDrinkingAge() makes more sense than isOverEighteen() as the legal drinking age varies from country to country, and there are other things than drinking to consider that are limited by age.
Note the not more and not less. There's no reference on why it should matter to use or not a number in the naming of a function/variable. It is just a case of what will be easily understood when you/others read the code.
doesnt make sense to avoid this in general..
its rather a question of style and when it actually makes sence in your context
The only actual restriction is that you cannot start a member name with a number. Other than that, it's a matter of style. Having said that, I cannot think of a member in the standard library that has a number in it. It's certainly rare to need this, but it can be useful. No need to be too dogmatic about these kinds of things.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have a page I am building, and our solution to a problem involved wrapping some code inside a function then calling that when required.
Now the page is growing, and each item has its own function. According to D. Crockford each function is put in a VAR anyway so:
function functionName(){}
is equivalent to:
var var1 = functionName(){}
So now we have LOTS of vars in the page (I have also written them specifically in the latter format as Mr. Crockford promotes) and I am getting worried this creates too many variables (not sure this will cause any issues, performance or otherwise). I am thinking of making a single Object Literal and adding each function as a value to a key. This I think will reduce all these vars into a single manageable unit and reduce the amount of variables I am using (and avoid any potential issues) - or will it?
Thanks!
var keyword is actually being used in order to manage variable scope.
Not using var keyword makes the variable a global one. The memory occupied by the variables are cleared when the variable isn't used anymore. Most of the modern browsers contains a garbage collector responsible for freeing up the unused spaces. So it's suggested that using var keyword in blocks would make your js interpreter search less for the variable, otherwise it will search the whole document in order to get the value.
In performance terms it doesn't matter, you can use as many variables as you want, the performance only will be affected by the tasks performed in the function.
As you keep increasing the variables, the heap limit set by the relevant JS engine will come into play.
For eg - V8 engine seems to have it set to 1.4 GB
If you do ever run out of that, it's high time you recheck the code & stop blaming JS.
On a serious note, from a practical point of view, that's an enormous limit, which tells you that you don't need to worry about it so much.
Besides your friendly neighborhood GC will always keep cleaning up & ensure you live lavishly with variables.
Encapsulating your code in a namespace is a good idea but you won't save memory or get a performance boost that way. From performance perspective both ways you've shown are the same.
There is a convention to avoid nameclashing however based on reverted domain - imagine a JS lib made for SO:
// The following two lines are to protect namespace from overwriting and allow to
// extend them easily
if (!com) var com = {};
if (!com.stackoverflow) com.stackoverflow = {};
com.stackoverflow.renderSomething = function(){
// Some very clever code here
};
There is nothing else you can gain this way but it's worth to organize your code this way.
And just to clarify:
function functionName(){};
is almost the same as
var functionName = function(){};
Almost because in the first form functionName is defined at parse-time and the latter form defines functionName at run-time.