Reputation: 1105
I have been using javascript for a while now, and have authored my first content that has been used by other people.
The main reaction has been that my content does not play well with other code.
Unfortunately javascript does not have a lot of the normal tools for creating non-conflicting libraries, like namespaces and classes.
So what are the basic standards and tools for writing non-conflicting libraries in JS?
Upvotes: 1
Views: 1489
Reputation: 1105
Javascript is a beautiful and broken programing language. Many programers coming from other languages often find its nature quite confusing if not down right annoying.
Javascript is missing a lot of the tools classical languages use to create clean classes and interfaces. But this does not mean that you can't write great libraries in JS, it just means that you need to learn how to use the tools it offers.
IMO the best resources on the subject of good modular code are:
Douglas Crockford's : javascript the good parts
Adequately Good's : Module Pattern: In-Depth
Paul Irish's : 10 things I learned from the jQuery Source
In all of these, the issue of conflicting code is addressed with at least the following two practices.
(function(dependency , undefined ) {
...dostuff...
})(dependency)
Wrapping your library in a IFFE is incredibly useful because it makes an immediate closure.This keeps you from over-populating the global namespace.
In addition : the above code Passes in the libraries dependencies
as parameters. This both improves performance, and reduces side effects. For example jQuery passes in window via:(function(window){})(window)
Last but not least, we add but don't define the parameter undefined
. This is often referred to as the idiot test. If someone changed undefined
somewhere else in their code it could easily cause all kinds of trouble for your library. (function(undefined) {})()
fixes this by "Not defining undefined" thus making it work as intended.
var _myLibrary = window.myLibrary;//Backs up whatever myLibrary's old value was
myLibrary = function(){...dostuff...};
myLibrary.prototype = {
getConflict : function() {
return window.myLibrary === myLibrary ?
_myLibrary || false : false;
};
}
Conflict Methods are very important when you do not know what other libraries yours will be used with. The above method is similar to jQuery's 'noConflict'.
In short, getConflict
returns the overwritten myLibrary variable. If nothing was overwritten, then it returns false.
Having it return false is extremely useful as it can be used in an if
statement like so.
if(myLibrary.getConflict()){
var foo = Object.create(myLibrary.getConflict());
}
Upvotes: 4