• later method

    Object.prototype.later = function (msec, method) {
        var context = this,
        args = Array.prototype.slice.apply(arguments, [2]); 
        if (typeof method === 'string') { 
            method = context[method]; 
        } 
        setTimeout(function () { 
            method.apply(context, args); 
        }, msec); 
        return context; 
    }; 
    
    
  • fixed a closure bug

    Closure refer the ability that a function can access and manipulate external variable from with a function. Sometimes, this is not good because the if a function depends on the external state. When the external state changes, the function may produce unexpected result.

  • efficency string operation

    Because string is immutable in JavaScript, concatenation with array.join('') is much efficient. The following code use all the chinese characters. Click here to show

  • the bind function

    John Resig has page Learning Advanced JavaScript to explain how the following script works.

    // The .bind method from Prototype.js 
    Function.prototype.bind = function(){ 
      var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift(); 
      return function(){ 
        return fn.apply(object, 
          args.concat(Array.prototype.slice.call(arguments))); 
      }; 
    };
    

    His explanation is wonderful. And this piece of code is simple, powerful. But it maybe still hard for anyone to understand without any explanation. So I refactored it as follow, and add one use case.

    Function.prototype.bind = function() {
        var function_to_be_bound = this;
        //convert argements into a real array
        var args = Array.prototype.slice.call(arguments); 
        //the first element in the array is the context_object to be bound to
        var context_object = args.shift();
        //the rest of elements in the array is the prefilled parameter
        var binding_parameters = args;
    
    
  • memoried function

     Function.prototype.memorized = function(key) {
         this._values = this._values || {};