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 ...
Related
While reading "Object-Oriented JavaScript" on Mozilla's website, I stumbled upon this note:
It's important to note that in JavaScript there's no language-level difference between regular objects and namespaces.
However, the note is not clear about what is meant by "language-level difference".
Does it mean there are two ways of writing the same thing?
Or that there are two terms that refer to the same thing?
You've taken the quote out of context. The answer is in the paragraph above the quote:
A namespace is a container which allows developers to bundle up functionality under a unique, application-specific name. In JavaScript a namespace is just another object containing methods, properties, and objects.
(Emphasis mine)
The quote:
It's important to note that in JavaScript there's no language-level difference between regular objects and namespaces.
Is just saying that this means a "namespace" is just a object used as a "namespace".
There are no "real" namespaces in JS.
Some languages have an actual namespace which is not the same thing as an object. JavaScript is not one of those languages, so objects are used for this purpose.
For example, the Math functions like Math.round and Math.abs, are all namespaced in the Math object. They aren't really contextual methods like toString is (at least not in any implementation I've found), just collected under an object to keep it organized. *
* They are technically methods, because they are accessible by a property on an object (a definition that technically makes all global functions methods because they are available through the global object (ie. window.Function())), but unlike methods like toString, or the methods of most console implementations like console.log they do not depend on the object they are called on and the this value is irrelevant. The Math object is used purely for namespacing, not because of the context it gives.
First, are you sure you know what a namespace is? Real Quick:
Let's use an analogy. On your computer you have files. But you don't just have files you have folders. Why?
Because if there were no folder every file name would have to be unique and it would be hard to keep things organized.
Same for variables names if you only had global variables. If you could only have global variables every variable name would have to be completely unique.
This would be very difficult to keep track of. Chances are you would probably end up using the same variable name by accident. Your code would act funny and it would be very difficult to track down the problem.
So what's the solution?
That's right put your variables into folders, ahem, sorry, I meant namespaces, put them into namespaces. I gotta figure out how to use the backspace key.
Anyway, languages like C# and Java let you do exactly this:
// C# - example of a language with built in support for namespaces
namespace MySpace {
class MyClass {
}
}
namespace Facebook {
class MyClass {
}
}
There no conflict because the classes are in different namespaces. Then in your code if you wanted to instantiate them you would write something like this:
// C# again (JavaScript code coming up soon - keep scrolling)
var myObject = new Facebook.MyClass();
That's great but JavaScript doesn't have a namespace keyword. Technically it doesn't have namespaces, what it does have is some really clever programmers.
Their solution? Use objects.
// JavaScript
var MySpace = {};
MySpace.MyFunction = function() {
// insert brilliant code here
};
var Facebook = {};
Facebook.MyFunction = function() {
// insert more brilliant code here
};
Now you have 2 functions with the "same" name that don't get in the way of each other. If you want to call the Facebook version of MyFunction you would write code like this:
// JavaScript
Facebook.MyFunction();
As you can see in these examples MySpace and Facebook are really objects, but they are objects that we are using only to separate functions and variables, which means we're using them for nothing more than to serve as namespaces.
One Extra Note
A lot of times you will see "namespace" objects declared like this:
var MySpace = MySpace || {};
This means MySpace = MySpace if the MySpace object already exists. Otherwise it's assigned a new empty object. This is a way of reusing the MySpace object/namespace in multiple files.
Each file adds it's own functions and variables to the same "namespace" object. For example:
var MySpace = MySpace || {};
MySpace.a = 10;
var MySpace = MySpace || {};
MySpace.b = 20;
You end up with one MySpace object with the variables a and b. This is true even if the code were in different files and even if you reverse the order.
It's important to note that in JavaScript there's no language-level difference between regular objects and namespaces.
It's saying that a "namespace" is not an actual type of component in JavaScript, but rather just another use of a plain old JavaScript object.
Today while working my mind was stack at some point in javascript.
I want to know that what is basic difference between
function FunctionName(){
//Code goes here;
}
And
var MyFuncCollection = new Object();
MyFuncCollection.FunctionName = function(){
//Code goes here;
}
Both are working same. Then what is difference between then. Is there any advantage to use function with object name?
I have read Question. But it uses variable and assign function specific variable. I want to create object and assign multiple function in single object.
The first one defines a global function name. If you load two libraries, and they both try to define FunctionName, they'll conflict with each other. You'll only get the one that was defined last.
The second one just has a single global variable, MyFuncCollection. All the functions are defined as properties within that variable. So if you have two collections that try to define the same function name, one will be FuncCollection1.FunctionName, the other will be FuncCollection2.FunctionName, and there won't be any conflict.
The only conflict would be if two collections both tried to use the same name for the collection itself, which is less likely. But this isn't totally unheard of: there are a few libraries that try to use $ as their main identifier. jQuery is the most prominent, and it provides jQuery.noConflict() to remove its $ binding and revert to the previous binding.
The short answer is, the method in object context uses the Parent Objects Context, while the "global" function has its own object context.
The long answer involves the general object-oriented approach of JavaScript, though everything in JavaScript is an object you may also create arrays with this Method.
I can't really tell you why, but in my experience the best function definition is neither of the top mentioned, but:
var myFunction = function(){};
It is possible to assign function to variables, and you may even write a definition like this:
MyObject.myMethod = function(){};
For further reading there are various online Textbooks which can give you more and deeper Information about this topic.
One main advantage I always find is cleaner code with less chance of overwriting functions. However it is much more than that.
Your scope changes completely inside the object. Consider the following code ::
Function:
function FunctionName(){
return this;
}
FunctionName()
Returns:
Window {top: Window, location: Location, document: document, window: Window, external: Object…}
Object:
var MyFuncCollection = new Object();
MyFuncCollection.FunctionName = function(){
return this;
}
MyFuncCollection.FunctionName()
Returns:
Object {}
This leads to some nice ability to daisy chain functions, amongst other things.
The first:
function functionName (){
//Code goes here;
}
Is a function declaration. It defines a function object in the context it's written in.
Notice: this doesn't have to be the global context and it doesn't say anything about the value of this inside it when it's invoked. More about scopes in JavaScript.
Second note: in most style guides functions are declared with a capitalized name only if it's a constructor.
The second:
var myFuncCollection = {};
myFuncCollection.functionName = function () {
//Code goes here;
};
notice: don't use the new Object() syntax, it's considered bad practice to use new with anything other then function constructors. Use the literal form instead (as above).
Is a simple assignment of a function expression to a property of an Object.
Again the same notice should be stated: this says nothing about the value of this when it's invoked.
this in JavaScript is given a value when the function object is invoked, see here for details.
Of course, placing a function on an Object help avoiding naming collisions with other variables/function declarations in the same context, but this could be a local context of a function, and not necessarily the global context.
Other then these differences, from the language point of view, there's no difference whatsoever about using a bunch of function declarations or an Object with bunch of methods on it.
From a design point of view, putting methods on an Object allows you to group and/or encapsulate logic to a specific object that should contain it. This is the part of the meaning of the Object Oriented Programming paradigm.
It's also good to do that when you wish to export or simply pass all these functions to another separate module.
And that's about it (:
I have been developing an app using JavaScript and all of my scripts are using the Module Pattern. Example:
var MyFunction = (function(){
}());
I saw where someone placed the name of the function inside the calling (). Example:
var MyFunction = (function(){
}(MyFunction));
I add this to some of my page and it still ran normal. Can anyone explain why it would be written with the name of the function inside the ()?
Can anyone explain why it would be written with the name of the
function inside the ()?
No. That coder didn't know quite what they were doing. (A lot tends to get left in when someone doesn't want to break working code)
That said, there are some situations where you would pass something into the IIFE, like window or jquery. You'd treat it as an argument on the inside, though.
The two versions you show are equivalent, but the second one is misleading: the parameter of the IIFE is not used.
You might want to pass (and use) an argument to a module IIFE to alias a dependancy:
var myModule = (function(t) {
//...
var someText = t('some.key');
//...
})(translationModule);
Another use which is opposite to your second example is to declare an argument to the IIFE, and pass nothing. This is to make sure that undefined is... undefined:
var myModule = (function(undefined) {
// Here you're safe from bizare third party code which might define 'undefined'.
})();
In his book Learning JavaScript Design Patterns, Addy Osmani shows several variations of the module pattern:
http://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript
Recommended reading.
Cheers!
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;
Nowdays, i create a .js file with a lot of functions and then I link it to my html pages. That's working but I want to know what's the best way (good practices) to insert js in my pages and avoid conflicts with scope...
Thank you.
You could wrap them in an anonymous function like:
(function(){ /* */ })();
However, if you need to re-use all of the javascript functions you've written elsewhere (in other scripts), you're better off creating a single global object on which they can be accessed. Either like:
var mySingleGlobalObject={};
mySingleGlobalObject.someVariable='a string value';
mySingleGlobalObject.someMethod=function(par1, par2){ /* */ };
or the alternative, shorter syntax (which does the same thing):
var mySingleGlobalObject={
someVariable:'a string value',
someMethod:function(par1, par2){ /* */ }
};
This can then be accessed later from other scripts like:
mySingleGlobalObject.someMethod('jack', 'jill');
A simple idea is to use one object that represents your namespace:
var NameSpace = {
Person : function(name, age) {
}
};
var jim= new NameSpace.Person("Jim", 30);
The best way is to create a new scope and execute your code there.
(function(){
//code here
})();
This is best used when the global scope is accessed at a minimum.
Basically, this defines an anonymous function, gives it a new scope, and calls it.
It's perhaps not the BEST way, but a lot of PHP systems (I'm looking at you, Drupal) take the name of their particular plugin and prepend it to all their function names. You could do something similar, adding the name of your capability to your function names - "mything_do_action()"
Alternately, you could take a more "OO" approach, and create an object that encapsulates your capability, and add all your functions as member functions on IT. That way, there's only one thing in global scope to worry about.