func-ception

This is one way to fake OO code in javascript, the outer function serves as a "class" and the inner functions as methods.

I don't really like it though.
 
This is one way to fake OO code in javascript, the outer function serves as a "class" and the inner functions as methods.

I don't really like it though.


its also useful in confining functions to a namespace...

since unlike a conventional compiled application... a web application usually runs javascript from various sources...

and since the chance exists for two different sources to have functions with identical names, its wise to confine your functions within a namespace you publish / know wont be duplicated.... the $ in jQuery for example.
 
My preference is using objects for namespaces:

var yourNamespace = {

foo: function() {
},

bar: function() {
}
};

Just have to remember to separate the functions with a comma
 
@scudsucker: It's essentially the same way of faking namespaces than using functions. By declaring a JSON object with behavioral functions you're getting the same result as declaring a function with behavioral functions. I actually prefer the latter, to be honest. Makes it much more scalable and extendable. JavaScript is intended as a prototyping language, so you can easily separate "classes" from one another in different files:

Code:
var Namespace = function () { };
Namespace.prototype.FirstClass = function () {
    this.Property;
    this.Behavior = function () { };
};
Namespace.prototype.SecondClass = function () {
    this.Property;
    this.Behavior = function () { };
};

You can have the namespace declaration(s) in one file and each class file in a separate file, to easily manage your code. JavaScript is incredibly powerful once you get to grips with the prototyping and dynamic behavior behind it. :D
 
its also useful in confining functions to a namespace...

since unlike a conventional compiled application... a web application usually runs javascript from various sources...

and since the chance exists for two different sources to have functions with identical names, its wise to confine your functions within a namespace you publish / know wont be duplicated.... the $ in jQuery for example.

Another useful feature of JavaScript is private scoping of code and functions, so it will never interfere with any other included script files:

Code:
(function (params) {
    alert("This code executes in its own private scope and no other external files will interfere with it");
})({ p1: "some value", p2: 123, p3: false });

It's a nifty trick of defining and executing a function in one single line...
 
Top
Sign up to the MyBroadband newsletter
X