So I'm working with WordPress and just spend an hour tracking down an issue between two plugins. They both use the same javascript variable 'd' but for different objects, so I had to change one of them to 'e', but those changes will be lost if the plugin ever updates.
There's thousands of plugins for WordPress, it's no surprise that programmers are using the same variables. Is there a way to prevent your own variables from being accidentally overwritten?
You can wrap your code with a function expression:
(function(){
var e = 1;
}())
In the code above, nothing outside the function can touch your variables and your variables don't destroy other global variables of the same name.
Just remember that since your variables are not visible outside the function, all of your code that refers to them must also be inside it.
The best practice is to use javascript namespaces.
var myApp = {}
myApp.id = 0;
Related
I was looking for this but could not find a question as simple as I want it. The problem is really simple: In angular js, should I use local variables, or properties of this (in cases when I don't need to use this).
Example:
// I need "this" here because I need this collection in template
this.collection = SomeService.fetchCollection();
// I can use either "foo" or "this.foo" here, which one is better?
this.fetchSomeData = function(type) {
var foo = AnotherService.foo(type);
return FooService.call(foo);
}
A local variable, so it can be cleaned up as soon as the method exits. Otherwise it would stay unused in the parent's namespace.
But in 99% of cases that will have no real-world effect, so it doesn't matter.
Because you haven't declared 'foo' as a var it will be a global here, which is bad. You should at least prefix it with 'var' so it's scoped to the function and not globally; it shouldn't be available outside the function.
in my opinion it is a good practice not to reveal everything and keep it encapsulated - for example, it avoids moving logic to view which is bad
also, consider that you have a for loop iteration over i variable - would you also use this.i for such purpose?
What are the benefits of using self executing functions with a framework, such as, Angular?
I am new to Angular but my understanding thus far is the module-based design gives most of the benefits that the Self executing function gives. What am I missing? Is it just a matter of style?
Here is an example by Ben Nadel. I really like the style but want to understand if there are any gains by writing Angular code this way or if it is mostly a style choice.
Mainly, it ensures that your code is not declared on the global scope, and any variables you declare remained scoped within your function.
In this case, it also has the benefit of declaring the objects required to run the code in one place. You can clearly see at the bottom that the angular and Demo objects are passed in, and nothing else. If the code was not wrapped in the function, you'd have to scan through the code to see what the dependencies were.
Personally, I prefer to use a module loader like RequireJS, which effectively forces you to follow this pattern.
That's kind of a opinion question. The main advantage I see on self executing functions is to not create global variables. I had never seen this pattern with angular.
On the example link you gave, it does not seem to have any advantage. The angular variable will exist anyway on a angular application, so you could use angular directly. And the Demo being a module, you can add controllers to it without without messing with the global scope.
I like a lot of self executing functions. But in this case I really don't see an advantage.
Daniel, you said: "if it is mostly a style choice".
I know at least two examples in javascript when "code style" is not only matter of preference but it causes different result.
Are semicolons optional? Not at all.
$scope.test = function() {
console.log('Weird behaviour!')
} //; let us comment it
(function() {} ()); //two functions seem to be independent
is equal to
$scope.test = function() {
console.log('Weird behaviour!')
}(function() {} ()); //but without semicolon they become the one
Another example of "code style" which is not related to self-executing functions:
var x = (function() {
return //returns undefined
{};
}());
alert(x);
/*
that is why, I suppose, while writing javascript code,
we put function brackets in the following "code style":
function() { //at the same line
return { //at the same line, this style will not lose the object
};
}
*/
Code style formation is dictated by unexpected results of such kind.
Last but not least.
With selfexecuting function: a closure is created on function call and keeps your vars local.
A closure is created on function call. That is why self-executing function is so convenient. As Daniel correctly mentioned it is a good place for keeping an independent code unit, this pattern is called module pattern. So when you move from pure javascript to specific framework or vise versa this independence enables code changes to be more fluid. The best case is just moving your module to an angular wrapper and reusing it.
So it is convenient for the purpose of code transmission from one technology to another. But, as I believe, it does not really make sence for specific framework.
I'm new to JavaScript, and have a simple (I presume) question regarding best practices for accessing variables in functions:
When should I declare a global variable, as opposed to simple passing a value into a function?
Declaring a global variable should only be used as an option of last resort.
Global variables are bad in general and especially so in javascript. There is simply no way to prevent another piece of javascript from clobbering your global. The clobbering will happen silently and lead to runtime errors.
Take the following as an example.
// Your code
myParam = { prop: 42 };
function operateOnMyParam() {
console.log(myParam.prop);
}
Here i've declared 2 global variables
myParam
operateOnMyParam
This might work fine while testing your javascript in isolation. However what happens if after testing a user combines your javascript library with my javascript library that happens to have the following definitions
// My code
function myParam() {
console.log("...");
}
This also defines a global value named myParam which clashes with your myParam. Which one wins depends on the order in which the scripts were imported. But either way one of us is in trouble because one of our global objects is dead.
There are many, many reasons.. but an easy one is.. The argument of a function only exists in the function, while it's running. A global variable exists all the time, which means:
it takes up memory until you manually 'destroy' it
Every global variable name needs to be unique
If, within your function.. you call another function.. which ends up calling the first function, all of a sudden you may get unexpected results.
In short: because the function argument only lives for a really short time and does not exist outside the function, it's much easier to understand what's going on, and reduced the risk of bugs greatly.
When dealing with framework-less JavaScript I'll store my simple variables and functions in an object literal as to not clutter up the global namespace.
var myObject = {
variableA : "Foo",
variableB : "Bar",
functionA : function(){
//do something
//access local variables
this.variableA
}
}
//call functions and variables
myObject.variableA;
myObject.functionA();
I have a number of aspx pages (50+).
I need to declare a number(5-7) of global variables in each of these pages.
Variables in one page independent of the other pages even though some might be same.
Currently I am declaring at the page top and outside of any function.
Should I approach this differently and is there any side effects of this approach?
If exact duplicate, please let me know.
Thanks
It is best practice to not clutter the global scope. Especially since other frameworks or drop-in scripts can pollute or overwrite your vars.
Create a namespace for yourself
https://www.geeksforgeeks.org/javascript-namespace/
More here: https://stackoverflow.com/search?q=namespace+javascript+global
Some examples using different methods of setting the vars
myOwnNS = {}; // or window.myOwnNS
myOwnNS.counter = 0;
myOwnNS["page1"] = { "specificForPage1":"This is page 1"}
myOwnNS.page2 = { "specificForPage2":"This is page 2", "pagenumber":2}
myOwnNS.whatPageAmIOn = function { return location.href.substring(location.href.lastIndexOf('page')+4)}
As #mplungjan says, best practice is to avoid global variables as much as possible.
Since window is global, you can declare a namespace at any time and within any function by using window.NAMESPACE = {};
Then you can access NAMESPACE globally and set your values on it as properties, from within the same or another function:
NAMESPACE = { var1:"value", var2:"value" /* etc */ };
If you can do all this within script files rather than directly in your page then so much the better, however I guess you may not have the values available in a static script.
One approach would be to declare the variable on "root" level, i.e, outside any code blocks before any other JS code tries to access it.
You can set global variables using window.variablename = value; in order to keep it clean superficially atleast.
Any best practices around it?
JavaScript collision is when you have two global objects with the same name, and one overwrites another. For example, you might reference two libraries that both use a function named $ at the root object (window) for a query function. The idea is that you should use as few global objects as possible. The best way to do this is to create a namespace for any JS you write, just like any other language:
var myApplication = {};
And then add any subsequent functions / objects inside the namespace:
myApplication.init = function () {
}
google sometimes better than stackoverflow
http://javascript.about.com/od/learnmodernjavascript/a/tutorial22.htm
I think it is a concept which detects when two objects collide, this technique is especially useful when creating javascript-based games.
This also refers to collision of different javascript libraries used in one page for example jquery and prototype used in one page and nothing works because of collision usually because of popular $ sign.
Javascript has first class, lexically scoped functions, in other words in side of a function, when you call a variable, it checks itself for an instance of that variable, then checks it's parent function.
<script>
var foo = "test1";
document.write(foo+"\n"); //test1+ a linebreak
(function(){
document.write(foo+"\n"); //test1+ a linebreak
var foo = "test2";
document.write(foo+"\n"); //test2+ a linebreak
})();
document.write(foo+"\n"); //test1+ a linebreak
</script>
I thought it was something that happens when a Mummy Javascript and a Daddy Javascript, who love each other very much want to eval a baby Javascript.
My teacher wasn't very clear on this point however ...