JavaScript Patterns

Stoyan Stefanov

Mentioned 28

Now that JavaScript plays such a key role in modern websites, programmers who once dismissed it as a language for amateurs find themselves immersed in JavaScript code. JavaScript Patterns identifies key problem areas you might face when working with the language, and provides coding and design patterns as solutions. JavaScript expert Stoyan Stefanov -- Senior Yahoo! Technical and architect of the performance optimization tool 'YSlow' 2.0 -- includes several examples for each pattern as well as practical advice for implementing it. Learn how to look at your application code through a patterns lens Use code and design patterns to write clean and maintainable JavaScript code Recognize antipatterns -- solutions that create more problems than they solve

More on Amazon.com

Mentioned in questions and answers.

I'm trying to write a function that either accepts a list of strings, or a single string. If it's a string, then I want to convert it to an array with just the one item. Then I can loop over it without fear of an error.

So how do I check if the variable is an array?


I've rounded up the various solutions below and created a jsperf test.

There is a nice example in Stoyan Stefanov's book JavaScript Patterns which suppose to handle all possible problems as well as utilize ECMAScript 5 method Array.isArray().

So here it is:

if (typeof Array.isArray === "undefined") {
    Array.isArray = function (arg) {
        return Object.prototype.toString.call(arg) === "[object Array]";
    };
}

By the way, if you are using jQuery, you can use it's method $.isArray()

I've been working almost exclusively on back-end tasks for the past few years, and I've just noticed that most JavaScript (and CoffeeScript) projects have got a helluva lot prettier in my absence.

I work primarily in a rails environment, and almost all my JavaScript/jQuery used to look like this:

$(an_element).an_event(function() {
  stuff_i_want_to_do;
})

$(another_element).some_other_event(function() {
  some_other_stuff_i_want_to_do;
})

Callbacks aside, that's pretty much been it.

Anyhow, was just browsing through some other folks' code and noticed many javascripters have been getting a lot prettier in my absence. This isn't complex, but it's typical of the newer/better approach to JavaScript I've been seeing:

jQuery -> 
  if $('#products').length
    new ProductsPager()

class ProductsPager
  constructor: (@page = 1) ->
    $(window).scroll(@check)

  check: =>
    if @nearBottom()
      @page++
      $(window).unbind('scroll', @check)
      $.getJSON($('#products').data('json-url'), page: @page, @render)
#

  nearBottom: =>
    $(window).scrollTop() > $(document).height() - $(window).height() - 50

  render: (products) =>
    for product in products
      $('#products').append Mustache.to_html($('#product_template').html(), product)
    $(window).scroll(@check) if products.length > 0

I've been looking for resources on modern best practices/patterns for JavaScript (and/or CoffeeScript), but I haven't had much luck. So in short, where should I look to be brought up to speed re: best javascript/coffeescript modern patterns & practices?

You need a good book like "JavaScript Patterns" accompanied by an equally good ide/environment like "Fiddle" for practicing.

I stumbled upon that performance test, saying that RegExps in JavaScript are not necessarily slow: http://jsperf.com/regexp-indexof-perf

There's one thing i didn't get though: two cases involve something that i believed to be exactly the same:

RegExp('(?:^| )foo(?: |$)').test(node.className);

And

/(?:^| )foo(?: |$)/.test(node.className);

In my mind, those two lines were exactly the same, the second one being some kind of shorthand to create a RegExp object. Still, it's twice faster than the first.

Those cases are called "dynamic regexp" and "inline regexp".

Could someone help me understand the difference (and the performance gap) between these two?

Nowadays, answers given here are not entirely complete/correct.

Starting from ES5, the literal syntax behavior is the same as RegExp() syntax regarding object creation: both of them creates a new RegExp object every time code path hits an expression in which they are taking part.

Therefore, the only difference between them now is how often that regexp is compiled:

  • With literal syntax - one time during initial code parsing and compiling
  • With RegExp() syntax - every time new object gets created

See, for instance, Stoyan Stefanov's JavaScript Patterns book:

Another distinction between the regular expression literal and the constructor is that the literal creates an object only once during parse time. If you create the same regular expression in a loop, the previously created object will be returned with all its properties (such as lastIndex) already set from the first time. Consider the following example as an illustration of how the same object is returned twice.

function getRE() {
    var re = /[a-z]/;
    re.foo = "bar";
    return re;
}

var reg = getRE(),
    re2 = getRE();

console.log(reg === re2); // true
reg.foo = "baz";
console.log(re2.foo); // "baz"

This behavior has changed in ES5 and the literal also creates new objects. The behavior has also been corrected in many browser environments, so it’s not to be relied on.

If you run this sample in all modern browsers or NodeJS, you get the following instead:

false
bar

Meaning that every time you're calling the getRE() function, a new RegExp object is created even with literal syntax approach.

The above not only explains why you shouldn't use the RegExp() for immutable regexps (it's very well known performance issue today), but also explains:

(I am more surprised that inlineRegExp and storedRegExp have different results.)

The storedRegExp is about 5 - 20% percent faster across browsers than inlineRegExp because there is no overhead of creating (and garbage collecting) a new RegExp object every time.

Conclusion:
Always create your immutable regexps with literal syntax and cache it if it's to be re-used. In other words, don't rely on that difference in behavior in envs below ES5, and continue caching appropriately in envs above.

Why literal syntax? It has some advantages comparing to constructor syntax:

  1. It is shorter and doesn’t force you to think in terms of class-like constructors.
  2. When using the RegExp() constructor, you also need to escape quotes and double-escape backslashes. It makes regular expressions that are hard to read and understand by their nature even more harder.

(Free citation from the same Stoyan Stefanov's JavaScript Patterns book).
Hence, it's always a good idea to stick with the literal syntax, unless your regexp isn't known at the compile time.

Similar, but not the same as, How to enable ECMAScript "use strict" globally?

I have bought JavaScript Patterns and it recommends enabling use strict. Adding it to the two dozen javascript files would be a bit of a chore, so enabling it globally would be nice. I originally thought about adding to the top of my main.js like this:

"use strict" 
require({
    priority: ["jquery", "raphael", "myapp"] 
});

However I then thought that it maybe would only enable it for that file. I then thought about this:

<script data-main="lib/main" src="lib/require.js">"use strict"</script>

Would either of these enable ECMAScript 5 strict mode globally?

The specification says:

Because strict mode is selected at the level of a syntactic code unit, strict mode only imposes restrictions that have local effect within such a code unit. Strict mode does not restrict or modify any aspect of the ECMAScript semantics that must operate consistently across multiple code units.

(Section 4.2.2)

So the question is: Are different script tags different syntactic code units?

V8 (the JavaScript engine inside Chrome) appears to believe that they are separate and so putting a single "use strict"; in global scope at the top of your page would not work. Perhaps it's specified somewhere I haven't found yet, but in any case, it's a reasonable interpretation.

Assuming no declaration for foo that isn't shown, this code falls prey to The Horror of Implicit Globals in normal mode:

function test() {
    try {
      foo = "bar";
      display("foo = " + foo);
    }
    catch (e) {
      display("Exception: " + e);
    }
}

In normal mode, that creates a new global variable foo with the value "bar" and shows the "foo = bar" message. In strict mode, an exception is thrown because foo is undefined.

If I put this script tag in a page:

<script>
"use strict";
function test() {
    try {
      foo = "bar";
      display("foo = " + foo);
    }
    catch (e) {
      display("Exception: " + e);
    }
}
</script>

...I get the exception as expected (live example). If I put them in separate script tags, though:

<script>
"use strict";
</script>
<script>
function test() {
    try {
      foo = "bar";
      display("foo = " + foo);
    }
    catch (e) {
      display("Exception: " + e);
    }
}
</script>

I don't get the exception (on V8) (example). And that's reasonable if you think about how the browser and the JavaScript engine are interacting.

And similarly, if the function is off in another file and I do this:

<script>
"use strict";
</script>
<script src="/inatoq"></script>

I don't get the exception (example), presumably for the same reason.

Note that your example tag here:

<script data-main="lib/main" src="lib/require.js">"use strict"</script>

is invalid. A script tag may either have a src attribute or content, but not both. (Well, basically; details here [HTML5] and here [HTML 4.01].) If it has a src element, the browser is supposed to disregard the content, and most do. Most. :-)

The following code works, and while I understand why it works, I haven't seen it anywhere. I assume this is because all the other design patterns are much better.

I would still have expected to see the example as a cautionary tale along the line but I have not.

Sure, it is awful, especially with the example below which I chose because it is clear what it does but:

What is this pattern called?

Is it commonly used?

Are there any legitimate projects that use this pattern?

var add = function container (val) {

  addFunc = function f (val, undefined) {
  addFunc.total += val;
  return addFunc;
  };

addFunc.total = 0;

return addFunc(val);
};

alert(add(1)(2)(3).total);
alert(add(1)(2)(33).total);

Edit: Variable name change so that the code works in IE.

This is called Currying wikipedia. From the name of Haskell Curry wikipedia ( but originally developped by Moses Ilyich Schönfinkel wikipedia ).

A technique of transforming a function that takes multiple arguments (or an n-tuple of arguments) in such a way that it can be called as a chain of functions each with a single argument(partial application).

From JavaScript Patterns form 2010:

When to Use Currying - When you find yourself calling the same function and passing mostly the same parameters,then the function is probably a good candidate for currying. You can create a new function dynamically by partially applying a set of arguments to your function. The new function will keep the repeated parameters stored (so you don’t have to pass them every time) and will use them to pre-fill the full list of arguments that the original function expects.

Another article for currying from Dustin Diaz.

In this snippet of Google Closure javascript code involving a constructor, why is goog.base(this); necessary? Doesn't Foo already inherit from Disposable with goog.inherits(foo, goog.Disposable);?

goog.provide('Foo');

/**
 * @constructor
 * @extends {goog.Disposable}
 */
Foo = function() {
  goog.base(this);
}     
goog.inherits(foo, goog.Disposable);

foo.prototype.doSomething = function(){
  ...
}

foo.prototype.disposeInternal = function(){
  ...
}

goog.inherits(childConstructor, parentConstructor)

goog.inherits() establishes the prototype chain from the child constructor to the parent constructor.

/**
 * Inherit the prototype methods from one constructor into another.
 * @param {Function} childCtor Child class.
 * @param {Function} parentCtor Parent class.
 */
goog.inherits = function(childCtor, parentCtor) {
  /** @constructor */
  function tempCtor() {};
  tempCtor.prototype = parentCtor.prototype;
  childCtor.superClass_ = parentCtor.prototype;
  childCtor.prototype = new tempCtor();
  /** @override */
  childCtor.prototype.constructor = childCtor;
};


In addition to prototype properties, constructors may have "own" properties (i.e. instance-specific properties added to this). Since goog.inherits() does not call the parent constructor, own properties are not copied to the child constructor and any initialization code in the parent does not get executed. For these reasons, the standard pattern is to chain constructors as in the following example.

/**
 * @param {string} name The parent's name.
 * @constructor
 */
var Parent = function(name) {
  /**
   * @type {string}
   * @private
   */
  this.name_ = name;
}

/**
 * @param {string} name The child's name.
 * @constructor
 * @extends {Parent}
 */
var Child = function(name) {
  Parent.call(this, name);
}
goog.inherits(Child, Parent);


goog.base(self, opt_methodName, var_args)

goog.base() is a helper function for calling parent methods so that you do not need to explicitly use call() or apply().

If [goog.base()] is called from a constructor, then this calls the superclass contructor with arguments 1-N.

If this is called from a prototype method, then you must pass the name of the method as the second argument to this function. If you do not, you will get a runtime error. This calls the superclass' method with arguments 2-N.

This function only works if you use goog.inherits to express inheritance relationships between your classes.

In Closure code it is common to chain constructors with goog.base() rather than calling the parent constructor explicitly.

/**
 * @param {string} name The child's name.
 * @constructor
 * @extends {Parent}
 */
var Child = function(name) {
  goog.base(this, name);
}
goog.inherits(Child, Parent);


Further Reading

I saw the following code in the JavaScript Patterns book by Stoyan Stefanov (edited to remove extra fat):

function Universe() {
    var instance = this;
    Universe = function() {
        return instance;
    }
}

Universe.prototype.nothing = true;
var uni = new Universe();
Universe.prototype.everything = true;
var uni2 = new Universe();

uni.nothing;     // true
uni2.nothing;    // true, but I was expecting undefined
uni.everything;  // undefined
uni2.everything; // undefined, but I was expecting true

I was expecting nothing to be assigned to the original function's prototype, and everything to be assigned to the closure's prototype (since the second assignment happens after redefinition). However, the output shows that something odd is going on, and the book really doesn't explain it. I also noticed that:

  1. Universe.prototype does point to a different object after the function is redefined, as I expected.
  2. Further instances created after the redefinition still get the original prototype object as their __proto__. That's what I don't understand.

Could anyone explain, please?

uni and uni2 are the same object because the value of instance is returned in both versions of the Universe function.

Here is the same code but without instance returned from the redefined Universe: http://jsfiddle.net/nmaBn/

Please provide your thoughts with respect to Javascript only! I am aware of classes and classical inheritance but not at a great detail.

As far as I know, constructors are used as prototypes for other objects. For example, I could create a car constructor and give it objects such as hondaCivic, toyotaCamry, etc. Are there any other important things I should know about constructors?

Furthermore,

  1. What is the purpose of a constructor, apart from what I have already stated?
  2. What are the benefits / disadvantages of a constructor?

A constructor is just a normal function. There is nothing special about it inherently.

All functions have a property called prototype.

If you write

var myInstance = new MyFuction();

JavaScript does something special with your function when it executes it.

It sets the value of this inside the function body to be myInstance. Additionally, it creates a reference to MyFunction.prototype and stores it as an internal property of myInstance.

When your code is executing, the rule that the interpreter follows is such that, if you try to access a property on myInstance that it can't find, it will follow that reference to the function's prototype and look there. This forms a chain, known as the prototype chain that leads all the way up to Object.prototype.

Here's an example:

function Dog(name, breed) {
  this.name = name;
  this.breed = breed;

  //if you don't specify a return value, `this` will be returned
}

Dog.prototype.speak = function() {
  alert('Ruff, I\'m ' + this.name + ' the talking ' + this.breed);
}

var myDog = new Dog('buttercup', 'poodle');
myDog.speak();

The snippet above works, but if you run: console.log(myDog) you'll see that it does not have a speak method. the speak method was found in it's prototype.

This means that all 'instances' of Dog that are created will all share the same speak method.

So, If I create another dog, it will be able to speak aswell:

var tommysDog = new Dog('rosco', 'pitbull');
tommysDog.speak(); //tommy's dog can speak too

  
    function Dog(name, breed) {
      this.name = name;
      this.breed = breed;

      //if you don't specify a return value, `this` will be returned
    }

    Dog.prototype.speak = function() {
      alert('Ruff, I\'m ' + this.name + ' the talking ' + this.breed);
    }

    var myDog = new Dog('buttercup', 'poodle');

    var tommysDog = new Dog('rosco', 'pitbull');
    tommysDog.speak();

It also means that if I change the value of Dog.prototype.speak at run time, all instances will be affected.


Note: technically, functions do have a constructor property but it's not that important and it would just confuse you more if I tried to explain it here.

I suggest you read the mozilla docs

Additionally, I suggest you read this book. You'll learn a lot about proper design.


Also note that this is just one way to achieve code re-use. You don't have to go through prototypes at all. In fact JavaScript has methods that let you supply arbitrary values as the value of this to functions as an argument.

This means that, even though my pet lizard can't normally speak, I can just borrow the method from Dog.prototype by utilizing a method like call() or apply(). (All functions have these methods because they 'inherit' them from Function.prototype.)

function Dog(name, breed) {
  this.name = name;
  this.breed = breed;

  //if you don't specify a return value, `this` will be returned
}
Dog.prototype.speak = function() {
  alert('Ruff, I\'m ' + this.name + ' the talking ' + this.breed);
};



function Lizard(name, species) {
  this.name = name;
  this.species = species;
}

Lizard.prototype.speak = function() {
  var pretend_dog = { name: this.name, breed: this.species };
  Dog.prototype.speak.call(pretend_dog);
};

var myLizard = new Lizard('larry', 'chamelion');
myLizard.speak();

I have implemented Infinite scrolling(i.e Load records when the scrollbar reaches the bottom of the div). It works fine but after loading too many records on the page, the page becomes too heavy & causes slow rendering. Actually, I am using this technique as a replacement of a gridview so, how do i manage heavy DOM in this scenario?

  1. Reduce the DOM elements to minimum.
  2. Minimize the number of wrappers.
  3. Minimize the acces to the DOM elements, which includes ( yahoo suggestions ):
    • Cache references to accessed elements
    • Update nodes "offline" and then add them to the tree
    • Avoid fixing layout with JavaScript
  4. If there is any computation which can be reduced, like getting the number of rows ( don't calculate it everytime, just add the number of the new rows to the current ), cache it ( memoization wikipedia )

If you have any type of iteration over a collection of DOM elements and you don't use jQuery to iterate, use this (suggestions by JavaScript patterns):

for (var iteration = 0, limit = lengthOfElements; iteration++; iteration < limit)

or

for (var i = myarray.length; i--; )

I'm designing an OOP inheritance pattern for many applications I'm building. Javascript has many ways of doing this, but I stumbled on a pattern I really like. But now I'm struggling with the need for a separation of classes and instances.

I have a base object called Root. And it has a main method called inherit. To create a new object you use

var Person = Root.inherit({
    name : "",
    height : 0,
    walk : function() {},
    talk : function() {}
});

Then to create an "instance" you would

var sally = Person.inherit({
    name : "sally",
    height : "5'6"
});

sally can .talk() and she can walk() and she has a .name and a .height You can make more people the same way.

If you want a constructor you use

var Person = Root.inherit({
    _construct : function() {
        // do things when this object is inherited from
    },
    name : "",
    height : 0,
    walk : function() {},
    talk : function() {}
});

It also has the ability to have init, when the object is first defined in code (singletons use this)

var Person = Root.inherit({
    _init : function() {
        // called at runtime, NOT called if an object is inherited from me
    },
    name : "",
    height : 0,
    walk : function() {},
    talk : function() {}
});

So as you can see, everything uses .inhert(). There are no classes and no instances really. Everything is an instance of something. The only real problem I found so far is that there is no concept of "type", but you can always just check for a method if you need to. Also you can't protect a 'class', as a 'class' can be changed during execution if the developer accidentally changed it, or meant to change it.

So my question is: Is there a need in javascript to have an explicitly and controlled separation of class structure and instances of the class? Are there any issues with treating every object as an instance?

No there's no need since Javascript is a Prototypal based language, meaning that classes are not involved. You are just creating clones of the objects.

http://en.wikipedia.org/wiki/Prototype-based_programming

As far as the concept of type, the type is object.

A good read for more info about this would be Javascript Patterns by Stoyan Stefanov he has several different creational patterns that address your concerns, including examples that implement Design Patterns from the gang of four's design patterns. http://www.amazon.com/JavaScript-Patterns-Stoyan-Stefanov/dp/0596806752

Lets say I have the following Backbone view which loads two links, one with the anchor text "test1" and the other with the anchor text "test2".

I bind a click event and I get the HTML of the link that was clicked and store it inside the clickedHtml variable.

Now, this view is loaded by a Backbone router.

When the user clicks either one of the two links (test1 or test2) another view called "main" will be loaded by the router.

Now, how can I pass the "clickedHtml" variable to that view?

Should I use LocalStorage?

Should I declare it globally like window.clickedHtml?

Is there a better way?

Ty!

// file: views/test.js
            define([
                'jquery', 
                'underscore', 
                'backbone'
            ], function($, _, Backbone) {

                var Test = Backbone.View.extend({

                    el : '.test',

                    initialize : function () {

                        var that = this;

                        that.$el.html('<a href="#/main">test1</a><br /><a href="#/main">test2</a>');


                    },

                    events : {

                        'click .test a' : 'click'

                    },

                    click : function (e) {

                        var clickedHtml = $(e.target).html();

                    }

                return Test;

            });

Here is my router:

// file: router.js

    define([
        'jquery', 
        'underscore', 
        'backbone',
        'views/test',
        'views/main'
    ], function ($, _, Backbone, Test, Main) {

        var Router = Backbone.Router.extend({

            routes: {
                '' : 'home',
                'test' : 'test'
            }
        });

        var initialize = function () {

            var router = new Router();

            router.on('route:home', function () {

                var main = new Main();

            });

            router.on('route:test', function () {

                var test = new Test();
            });

            Backbone.history.start();
        }

        return { 

            initialize : initialize 
        }
    });

Architecturally speaking, your aim should be to keep your code generic & reusable.

One of the main things you don't want to do in a situation like this is to pass direct references from one object to another - if you end up changing the setup of one of the objects, or you need to pass data from another object as well, this can get messy really fast.

One design pattern that's widely used in situations like this is a mediator. Also known as "pub/sub" you can have a centralized standalone object that mediates information between objects. Certain objects will publish information and other objects can subscribe to them. The mediator acts as an intermediary so that the objects never have to communicate directly with each other. This makes a much more generic, reusable and maintainable solution.

More info here:

http://addyosmani.com/largescalejavascript/#mediatorpattern,

Javascript Patterns

On the Backbone side of things... If you've used Marionette, you may have come across a complimentary mini-library (also implemented by Derick Bailey) called wreqr. You can use this to create a simple mediator with low-overhead in your Backbone applications.

https://github.com/marionettejs/backbone.wreqr

It basically allows you to use backbone style events across objects. Example below:

First, you need to create a globally accessible mediator object, or add it to your app namespace or use require.js:

var mediator = new Wreqr.EventAggregator();

inside View #1

events : {
    'click .test a' : 'click'
},

click : function (e) {
     var clickedHtml = $(e.target).html();

     // trigger an 'element:click' event, which can be listened to from other
     // places in your application. pass var clickedHtml with the event
     // (passed to the arguments in your eventhandler function).
     mediator.trigger('element:click', clickedHtml); 
}

Inside View #2

initialize: function(){
    //...
    this.listenTo(mediator, 'element:click', this.myEventHandler, this);
}

myEventHandler: function(elem){
    // elem = clickedHtml, passed through the event aggregator
    // do something with elem...
}

I am having a Good knowledge in JavaScript, I am in passion to know more and in depth about it. So i am start searching for the base or structural level and also various concept like event delegate, event bubbling etc., Is there is any resource for it.

I am trying to understand what function (global) means in code below, and is 'window' the parameter value passed to the function or its the name of a parameter rather than the parameter value?

May be this is simple JavaScript using an uncommon style of coding.

(function (global) {
var mobileSkin = "",
    app = global.app = global.app || {};
    app.application = new kendo.mobile.Application(document.body, 
                      { layout: "tabstrip-layout", skin:"flat"});
})(window);

The are common JavaScript patterns in this code:

  • The namespace pattern.
  • The immediate function pattern.

The Namespace Pattern

In a browser, the window object is the global scope object. In this example of code that you shared, the programmer created a immediately-invoked function expression and passes the global object window as a parameter, which in the context of the IIFE is linked to the local variable global.

The function, as it names suggests, is immediately invoked when this file is parsed by the browser.

From this point on, global is just an alias for the global scope object window, and the programer uses it to define a namespace app in it.

The namespace basically avoids cluttering the global scope with the objects you need to define and allows the programmer to be more in control of exactly what is defined within his custom scope.

The idea is that from this point forward, you should define all application globals within this customised scope and not within the window global scope, by this avoiding name collisions with other third-party libraries that you are using. This will be a pseudo-equivalent of packages or namespaces in other languages like Java or C#.

Stoyan Stefanov in his book JavaScript Patterns explains it as follows:

Namespaces help reduce the number of globals required by our programs and at the same time also help avoid naming collisions or excessive name prefixing.

JavaScript doesn’t have namespaces built into the language syntax, but this is a feature that is quite easy to achieve. Instead of polluting the global scope with a lot of functions, objects, and other variables, you can create one (and ideally only one) global object for your application or library. Then you can add all the functionality to that object.

The Immediate Function Pattern

The immediately-invoked function is another common JavaScript pattern. It is simply a function that which is executed right after it is defined.

Stefanov describes its importance as follows:

This pattern is useful because it provides a scope sandbox for your initialization code. Think about the following common scenario: Your code has to perform some setup tasks when the page loads, such as attaching event handlers, creating objects, and so on. All this work needs to be done only once, so there’s no reason to create a reusable named function. But the code also requires some temporary variables, which you won’t need after the initialization phase is complete. It would be a bad idea to create all those variables as globals. That’s why you need an immediate function—to wrap all your code in its local scope and not leak any variables in the global scope:

(function () {
   var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
   today = new Date(),
   msg = 'Today is ' + days[today.getDay()] + ', ' + today.getDate();
   alert(msg);
}()); // "Today is Fri, 13"

If this code weren’t wrapped in an immediate function, then the variables days, today, and msg would all be global variables, leftovers from the initialization code.

I want to use goog.addSingletonGetter() (http://closure-library.googlecode.com/svn/!svn/bc/4/trunk/closure/goog/docs/closure_goog_testing_singleton.js.source.html#line56) to add a getInstance() method to a class with a constructor that accepts arguments:

Foo = function(x, y) {...};

Is there a way for me to specify goog.addSingletonGetter(Foo, arg1, arg2)? Calls to Foo.getInstance() would then lazily return the instantiated Foo object.

Closure: The Definitive Guide on page 70 defines goog.addSingletonGetter() as follows:

For a class with a constructor that takes zero arguments, goog.addSingletonGetter() adds a static method to its constructor function named getInstance() that returns the same instance of that object whenever it is called. Generally, it should be used instead of the constructor function if it exists.

One approach would be to create a singleton following the Instance in a Static Property design pattern presented in JavaScript Patterns on page 143 with the addition of a static getInstance() function.

/**
 * @param {string=} opt_x
 * @param {string=} opt_y
 * @constructor
 */
Foo = function(opt_x, opt_y) {

  if(Foo.instance_) {
    return Foo.instance_;
  }

  /**
   * @type {string}
   * @private
   */
  this.x_ = goog.isDefAndNotNull(opt_x) ? opt_x : 'default_X';

  /**
   * @type {string}
   * @private
   */
  this.y_ = goog.isDefAndNotNull(opt_y) ? opt_y : 'default_Y';

  Foo.instance_ = this;
};


/**
 * Get the singleton instance of Foo.
 * @param {string=} opt_x
 * @param {string=} opt_y
 */
Foo.getInstance = function(opt_x, opt_y) {
  if (Foo.instance_) {
    return Foo.instance_;
  }
  return new Foo(opt_x, opt_y);
};

The advantage to using this pattern is that it protects you from accidentally constructing multiple instances in the event that someone were to write:

var foo = new Foo();

... 
// thousands of lines later
var snafoo = new Foo(); // Returns the singleton instance.   
var namespaced = {
    A: function(){
        function r(){
            //do some stuff
            return something;
        }

        var someProperty = 5;     

        function j(){
            //do some more stuff
            return something;
        }     
    },

    B: function(){   
        //can I call A and C?
        A.r();
        C.d();
    },

    C: function(){
        function d() {
            //do stuff we like
        }    
    }
}

Then I could do...

namespaced.A.j();

namespaced.C.d();

something = namespaced.A.someProperty;

right?

Would I need to do this too?

var something = new namespaced.A()?

If so does A() have a constructor? I'm really confused here :{

I'm trying to encapsulate my javascript so it's easy to maintain

Then I could do...

namespaced.A.j();
namespaced.C.d();
something = namespaced.A.someProperty;

No you couldn't. The function j and someProperty are only local to A and are not propagated to the outside. If you want to access them from the outside, you have to make them a property of the function, using this:

var namespaced = {
    A: function(){
        this.r = function(){
            //do some stuff
            return something;
        };

        this.someProperty = 5;     

        this.j = function(){
            //do some more stuff
            return something;
        };
    }
}

But you would still need to call var a = new namespaced.A() in order to access the functions.

If you want to call namespaced.A.j() directly, you would have to declare A as object, not as function:

var namespaced = {
    A: {
        r: function(){
            //do some stuff
            return something;
        },

        someProperty: 5,     

        j: function(){
            //do some more stuff
            return something;
        }     
    }
}

So it depends on what you want to achieve eventually... to get a better insight into these methods, I recommend JavaScript Patterns.

Regarding this question: What is the purpose of NodeJS module.exports and how do you use it?

I'm a Javascript beginner. In the referenced question...

mymodule.js code

var myFunc = function() { ... };
exports.myFunc = myFunc;

main js file

var m = require('./mymodule.js');
m.myFunc();

Is mymodule essentially a class file defining objects?

Node.js allows code to be separated into different modules. This modules are just javascript files that can expose functions or objects using the exports object.

  1. There are more details of this convention
  2. Nice documentation of the Node.js modules

There are no Classes in JavaScript but you can use patterns to emulate that behaviour. There is a question about implementing OOP patterns in JavaScript: what pattern to use when creating javascript class?

As a beginner there are very good books for JavaScript:

  1. JavaScript: The Good Parts
  2. JavaScript Patterns

They are short and will give you a very good insight of the JavaScript Language.

Would moving the inner function outside of this one so that its not created everytime the function is called be a micro-optimisation?

In this particular case the doMoreStuff function is only used inside doStuff. Should I worry about having local functions like these?

function doStuff() {
    var doMoreStuff = function(val) {
         // do some stuff
    }

    // do something
    for (var i = 0; i < list.length; i++) {
         doMoreStuff(list[i]);
         for (var  j = 0; j < list[i].children.length; j++) {
              doMoreStuff(list[i].children[j]);
         }
    }
    // do some other stuff

}

An actaul example would be say :

function sendDataToServer(data) {
    var callback = function(incoming) {
         // handle incoming
    }

    ajaxCall("url", data, callback);

} 

Not sure if this falls under the category "micro-optimization". I would say no.

But it depends on how often you call doStuff. If you call it often, then creating the function over and over again is just unnecessary and will definitely add overhead.

If you don't want to have the "helper function" in global scope but avoid recreating it, you can wrap it like so:

var doStuff = (function() {
    var doMoreStuff = function(val) {
         // do some stuff
    }
    return function() {
        // do something
        for (var i = 0; i < list.length; i++) {
            doMoreStuff(list[i]);
        }
        // do some other stuff 
    }
}());

As the function which is returned is a closure, it has access to doMoreStuff. Note that the outer function is immediately executed ( (function(){...}()) ).

Or you create an object that holds references to the functions:

var stuff = {
    doMoreStuff: function() {...},
    doStuff: function() {...}
};

More information about encapsulation, object creation patterns and other concepts can be found in the book JavaScript Patterns.

According to JavaScript Patterns book (p. 79), this should work:

 var ob = {
    fn: function foo(m) {alert(m);}
 };
 fn.apply(ob,['m']);

It doesn't work.

fn is not defined error thrown.

These 2 work OK:

ob.fn.apply(ob,['m']);

and

ob.fn.apply(null,['m']);

Why doesn't just fn.apply(ob,['m']) work? Can't get it.

fn doesn't work because it's not a variable in scope. If window.fn was defined, or var fn was defined elsewhere, then you'd be able to access it as fn.apply. Because neither of those are defined, you need to use the full path to the function on the object:

ob.fn.apply(...);

If you want fn to be defined, you could simply set it:

var ob,
    fn;

ob = {
  fn:function(){...}
};
fn = ob.fn;

fn.apply(ob, ...);

I have an index.php file that loads other php files via this javascript/ajax code:

function AJAX(elementID,url,showStatus){
var httpObject;
if (window.ActiveXObject) {
    httpObject = new ActiveXObject("Microsoft.XMLHTTP");
}
if (window.XMLHttpRequest){
    httpObject =  new XMLHttpRequest();
}
else {
    alert("Your browser does not support AJAX.");       
}

if (httpObject != null) {
    httpObject.onreadystatechange = function() {          
        if (elementID != false){                

            if (httpObject.readyState == 4 && httpObject.status == 200) {                  
                document.getElementById(elementID).innerHTML= httpObject.responseText;  

            } 
        }

    }

    httpObject.open("POST",url,true);
    httpObject.send(null);  
}
}

so for example I would load a file in inxex.php by:

<script>
AJAX("updateThisDiv", "/includes/contentpage.php", false)
</script>

which would paste the contents of "contentpage.php" into the div "updateThisDiv" but now if I have any javascript on "contentpage.php", it will not run, is there any way to do this?

I have looked at this: http://www.javascriptkit.com/script/script2/ajaxpagefetcher.shtml but its not exatcly what I was looking for.

I want to be able to update a section of my page without reloading the entire page and javascript must run

If you want to load Javascript on demand. This can be done by dynamically creating script tag. This pattern illustrated in Stoyan Stefanov book - Javascript Patterns

This snipped from the book:

Write a require function. Then call it like this:

require("extra.js", function () {
    functionDefinedInExtraJS();
});

Sample require function:

function require(file, callback) {

    var script = document.getElementsByTagName('script')[0],
        newjs = document.createElement('script');

    // IE
    newjs.onreadystatechange = function () {
        if (newjs.readyState === 'loaded' || newjs.readyState === 'complete') {
            callback();
        }
    };

    // others
    newjs.onload = function () {
        callback();
    };

    newjs.src = file;
    script.parentNode.insertBefore(newjs, script);
}

Live example found in http://www.jspatterns.com/book/8/ondemand.html

@Edit: more details specific to your case. I will try to make things simple:

Create fours files:

  • index.php : the test file.
  • code.js : actual code which have Ajax, getJS, getHTML functions
  • content.php : any PHP file that will print pure HTML without any JS
  • content.js : javascript code that you want to run dynamically.

index.php

<html>
    <head>
        <script src="code.js"></script>
    </head>
    <body>
        <input type="button" onclick="Ajax('content.php', 'd_html');" value="Fill from content.php"/>
        <div id="d_html"></div>
        <br>
        <input type="button" onclick="Ajax('content.js', 'd_js');" value="Fill from content.js"/>
        <div id="d_js"></div>
    </body>
</html>

content.php

<span>Hello, I am dynamic span came from content.php</span>

content.js

//Ana javascript code you want to run it by Ajax function should go inside this function
function executeJS(element){
   element.innerHTML = "<span>Hello, I am dynamic span came from content.js</span>";
}

code.js

//This function responsible for doing the ajax request for any file that will return pure HTML.
function getHTML(url, element){
    var i, xhr, activeXids = [
        'MSXML2.XMLHTTP.3.0',
        'MSXML2.XMLHTTP',
        'Microsoft.XMLHTTP'
    ];

    if (typeof XMLHttpRequest === "function") { // native XHR
        xhr =  new XMLHttpRequest();        
    } else { // IE before 7
        for (i = 0; i < activeXids.length; i += 1) {
            try {
                xhr = new ActiveXObject(activeXids[i]);
                break;
            } catch (e) {}
        }
    }

    xhr.onreadystatechange = function () {
        if (xhr.readyState !== 4) {
            return false;
        }
        if (xhr.status !== 200) {
            alert("Error, status code: " + xhr.status);
            return false;
        }

        element.innerHTML += xhr.responseText;
    };

    xhr.open("GET", url, true); 
    xhr.send("");
}

//This function will load javascript file on-demand and call executeJS function inside that file.
function getJS(url, element, cb){
    var newjs = document.createElement('script');

    // IE
    newjs.onreadystatechange = function () {
        if (newjs.readyState === 'loaded' || newjs.readyState === 'complete') {
            cb();
        }
    };

    // others
    newjs.onload = function () {
        cb();
    };

    newjs.src = url;
    element.appendChild(newjs);
}


//This is same as your function, but now can handle both PHP and JS files
function Ajax(url, id){
    var element = document.getElementById(id),
        regex = /\.js$/;
    if(!element){
        alert("Invalid ID");
        return false;
    }

    if(regex.test(url)){ //If url ends with JS, load using getJS
        getJS(url, element, function(){
            executeJS(element);
        });
    } else {
        getHTML(url, element);
    }
}

I'm fairly new to JavaScript. Can anyone share some good advice on getting started? I have a little experience in ActionScript 3 and have taken a few Java classes toward my CS degree but my background is of a designer transitioning into development. My goal is to become a well rounded front-end developer and I'd like to move beyond the simple slideshow animations and rollover effects. Any guidance/wisdom will be much appreciated!

I'll recommend some reading materials:

Beginner: JavaScript: The Definitive Guide

Intermediate: JavaScript Patterns

Advanced: JavaScript: The Good Parts

The best way to learn is practice. Write a simple application. When you are done, rewrite it so you learn what you did wrong last time. Perhaps, rewrite it again. Then, take on a new project. Repeat :).

In file meterA.js I have this

    window.MeterA = function(options)
    {
        return this.init(options);
    }

   MeterA.prototype = {
        init: function(options) {
            this.container = options.container;
            this.width = options.width;
            this.height = options.height;
            this.sliderSize = options.sliderSize;
            var Canvas = {
                meter: TBE.CreateRectCanvasElement (displayWidth, displayHeight),
                slider: TBE.CreateSquareCanvasElement (sliderSize)
            };
            Container.appendChild (Canvas.meter);
            Container.appendChild (Canvas.slider);
        }
    }

Then in file pane.html, I tried to initialise meter with:

var MeterA = new MeterA({
    container:  Div.meterA, 
    width:      GetNumberIgnoreUnit(Div.speedMeter.style.width, 2), 
    height:     GetNumberIgnoreUnit(Div.speedMeter.style.height, 2), 
    sliderSize: 10
});

But I get "MeterA is not a constructor" as error, why is it?

Smth along these lines should work :

var MeterA = (function () {

    // constructor
    var MeterA = function (options) {
        this.init(options);
    };

    // prototype
    MeterA.prototype = {
        init: function (options) {
            console.log(options);
        }
    };

    return MeterA;

})();

obj = new MeterA({
    opt1: 'sasa',
    opt2: false
});

I recomend Javascript Patterns 2010 for a more in-depth overview of the constructor pattern .

Another good read about javascript Essential JavaScript Design Patterns For Beginners, Volume 1.

I am trying to manage my code in javascript.What I have done is created two classes.

(function(){
 Main1 = function(){
    return this;
  }

Main1.prototype = {
Main1_method1 : function(){

},
Main1_method2 : function(){

}
}


})();

(function(){
 Main2 =function(){
        return this;
      }

    Main2.prototype = {
    Main2_method1 : function(){

    },
    Main2_method2 : function(){

    }
    }
})();

var MyInstance1 = new Main1();
var MyInstance2 = new Main2();

Question : I want to invoke one method in another.I want to call Main2_method1 in Main1_method1,but i have no idea how to do it.

I can use the classical model(function.prototype.method = function(){}) or the prototypal model(object.create).But I want to do this using the above method.

Inspired in the book "Javascript Patterns" by Stoyan Stefanov, you can use the "Public static Members" pattern, which allows you to define some special methods for an object accessible from everywhere. See that example:

    // Define a first object
    var Main1 = function(){
      var method1 = function() {
        return 'Main1.Method1';
      }

      var method2 = function(){
        return "I'm Main1 method2, executing: " + Main2.Method1();
      }

      return {
        Method1 : method1,
        Method2 : method2
      }
    }

    // Define a second object
    var Main2 = function(){
      var method2 = function() {
        return 'Main2.Method1';
      }
      return {
        Method2 : method2
      }
    }
    // Add a static method to Main2
    Main2.Method1 = function(){
      return 'Main2.Method1';
    }

    // Then you can execute the static method without 
    // instantiate its object...
    console.log(Main2.Method1()); // output: Main2.Method1

    // So, this will work
    var foo = new Main1();
    console.log(foo.Method2()); //output: I'm Main2 Method2, executing: Main2.Method1

There is not the only one solution, but in my opinion it is one of the best.

Back in your code, perhaps the problem is that you have defined the two objects in separate closures. So Main1 cannot use Main2 methods because of Main2 have been defined in a diferent scope.

I'm having some trouble using jQuery's plugin Facebox to process some data from a form. What I'm trying to accomplish is basically get the values of the number of selected checkboxes into an array and have it available in my popup to process it with PHP. I have something like this on a form page:

form.html

<input type="checkbox" name="equip" value="<?php echo $equip_id; ?>" />
<input type="checkbox" name="equip" value="<?php echo $equip_id; ?>" />
<input type="checkbox" name="equip" value="<?php echo $equip_id; ?>" />

<input type="button" name="replace" onClick="replace_equip()" />

There are more checkboxes, but I think these are enough to get started.

Here is replace_equip()

function replace_equip() {
  var nArr = new Array();
    $("input:checkbox[name=equip]:checked").each(function() {
  nArr.push($(this).val());
  $.facebox(function() {
    $.ajax({
      data: { name : nArr },
      error: function() {
      $.facebox("err");
      },
      success: function(data) {
      $.facebox(data);
      },
      type: "post",
      url: "test.php"
    });
  });
});
}

I'm trying to save the selected checkboxes into an array, in a way that I can use it for PHP processing in test.php.

I'm just getting started with jquery and javascript in general, so forgive any monster mistakes you may find!

To get started, there are a few stylistic issues with your code. First, you should opt not to use new syntax with Arrays, Objects, etc. Instead, declare your Array with something like var array = [];. Second, you're using an inline onClick, which should be avoided if you're using jQuery already. Instead, use something like $('input[name="replace"]').on('click', function() {...});. You should also consider using camelCase with your functions, and if you like underscores, use them with vars.

Now onto the meat of your question. I refactored your code like so:

$('input[name="replace"]').on('click', function() {
    replaceEquip();
});

function replaceEquip() {
  var array = [];
  $("input:checkbox[name=equip]:checked").each(function() {
    array.push($(this).val());
  });

  $.facebox(function() {
    $.ajax({
      type: "POST",
      url: "test.php",
      data: { name : array },
      error: function() {
        $.facebox("err");
      },
      success: function(data) {
        $.facebox(data);
      }
    });
  });
}

In your PHP code, you would json_decode() this array and work with it how you want. I also moved the type and url params to the top, as your error and success functions may get quite lengthy.

I would consider reading JavaScript Patterns (at least the Essentials chapter).

The past few sites I worked on and primarily event driven using jquery and i usually make my functions as so

function abc() {
    //do stuff
}
abc();

and

function foo() {
    var a = $('.aaa');
    var b = $('.bbb');
    var c = $('.ccc');

    function animal() {
        //do stuff
    }
    animal();

    function pet() {
        //do stuff
    }
    pet();
}
foo();

I know its not the best practice but, im still learning and it seems to work. I just would like to know the way I should handle this for now on.

Actually the code in your example (the first one) is not the best thing you can do if you're defining all these functions in the global scope (like properties/methods of the global object window). I prefer using module pattern http://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript I recommend you to read the whole book in the upper link. Another thing which is extremely useful - Stoyan Stefanov's JS Patterns book http://www.amazon.com/JavaScript-Patterns-Stoyan-Stefanov/dp/0596806752.

Another alternative of your example (the second one) is self-executing function:

(function () {
   //attaching events and doing all other stuff
}());

Self-executing functions are helping you to do some initialization work when loading the page for first time. You can attach events or/and do another stuff which you should do once. It's preventing you from polluting the global scope and doing init multiple times.

warning: jquery/javascript newbie in the house. I used the tutorial here to make an animation where an image swings back and forth on hover.

However, after the first hover event, the image will only go back and forth 1 time, whereas on the first hover event it swings back and forth 5 times (the number defined by swings variable). I want it to swing the same number of times on every hover event.

I have tried changing the rotation, swings, and swingcount variables and also trying to make the pendulumrest function match the swing function, and changing the if/else statement for pendulum swing. Nothing works - what am I doing wrong? Here is the code:

<script type="text/javascript">
(function($) {
    $(document).ready(function() {
        var rotation = 5; 
        var initrotation = rotation;
        var swingtime = 603;
        var swings = 5;
        var swingcount = 0; 
        var startatcentre = true;

        if (startatcentre == true) {
            initrotation = 0;
        }
        $('#pendulum-child').mouseenter(function() {
            function init() {
                $('#pendulum-parent').animate({rotate: initrotation}, 0, function () {
                    $('#pendulum-parent').css("display", "block");
                    rotation *= -1;
                    swingcount++;
                    pendulumswing();                    
                });
            }

            function pendulumswing() {
                $('#pendulum-parent').animate({rotate: rotation},swingtime, "swing", function(){
                     rotation *= -1;                     
                     if (swingcount >= swings) {
                        pendulumrest(); 
                    } else {
                        swingcount++;
                        pendulumswing();                        
                    }

                });
            }   

            function pendulumrest() {
                $('#pendulum-parent').animate({rotate: 0},(swingtime/1.5), "swing");    
            }

            init(); 
        });
    });
})(jQuery);    
</script>

If you walk through the code, then you will notice that the pendulum swing will stop only if swingcount >= swings. This means that the first time you move your mouse over the element, the swingcount will keep incrementing till it hits 5 and then the swinging stops.

The second time you move your mouse over the element, it will run the animation as per init (which I presume is resetting the position of the pendulum). It then calls pendulumswing which does an animation immediately. So you see the first swing. Once the first animation is over, it checks the swing count, which is still at its previous value of 6. This doesn't meet the condition and the pendulumrest is called instead.

So, as @Alex mentioned in his comment, you need to reset the value of swingcount to 0 before you start your animations. Implementing the thoughts in his comments, your code could be as follows:

<script type="text/javascript">
(function($) {
    $(document).ready(function() {
        var rotation = 5; 
        var initrotation = rotation;
        var swingtime = 603;
        var swings = 5;
        var swingcount = 0; 
        var startatcentre = true;

        if (startatcentre == true) {
            initrotation = 0;
        }

        function init() {
            swingcount = 0;
            rotation = 5;
            $('#pendulum-parent').animate({rotate: initrotation}, 0, function () {
                $('#pendulum-parent').css("display", "block");
                rotation *= -1;
                swingcount++;
                pendulumswing();                    
            });
        }

        function pendulumswing() {
            $('#pendulum-parent').animate({rotate: rotation},swingtime, "swing", function(){
                 rotation *= -1;                     
                 if (swingcount >= swings) {
                    pendulumrest(); 
                } else {
                    swingcount++;
                    pendulumswing();                        
                }

            });
        }   

        function pendulumrest() {
            $('#pendulum-parent').animate({rotate: 0},(swingtime/1.5), "swing");    
        }

        $('#pendulum-child').mouseenter(function() {
            init(); 
        });
    });
})(jQuery);    
</script>

Btw, Javascript Patterns is a very good book for learning JS. While it's not exactly a beginners book, he does explain everything properly. And I personally find it a lot more readable than the Good Parts book.

What is the difference between:

var name = function() { //stuff to do };

{name : function() { //stuff to do } };

function name() { //stuff to do };

As written by Stoyan Stefanov in "JavaScript Patterns":

In function declarations and named function expressions, the name property is defined. In anonymous function expressions, it depends on the implementation; it could be undefined (IE) or defined with an empty string (Firefox, WebKit):

function foo() {} // declaration
var bar = function () {}; // expression
var baz = function baz() {}; // named expression

foo.name; // "foo"
bar.name; // ""
baz.name; // "baz"

The name property is useful when debugging code in Firebug or other debuggers. When the debugger needs to show you an error in a function, it can check for the presence of the name property and use it as an indicator. The name property is also used to call the same function recursively from within itself. If you were not interested in these two cases, then an unnamed function expression would be easier and less verbose.

The case against function declarations and the reason to prefer function expressions is that the expressions highlight that functions are objects like all other objects and not some special language construct.