Inherit jQuery-like pattern

96 views Asked by At

Given the following code (jQuery pattern, I suppose):

        function child(){
            return new child.methods.init();
        }

        child.methods = child.prototype = {
            init: function(){
                return this;
            },
            test: function(){
                console.log('test');
                return this;
            }
        }

        //this code doesn't work
        child.methods.prototype = {
            test1: function(){
                console.log('test1');
                return this;
            }
        }

        child.methods.init.prototype = child.methods;

        //Using child chaining api. test() will work, but test1() will not.
        child().test().test1();

I need to inherit child from other object (object literal is given to simplify). How can I inherit child function pattern from object?

1

There are 1 answers

3
sachin kumar On BEST ANSWER

Child.method is iteself child.prototype. Why you are creating a new prototype attribute inside child.prototype/child.methods. You can acheive chaining as per your requirement.

  // Extend properties of existing methods/functions
  function extendProperties (base, extension) {
    for ( var property in extension) {
      try {
        base[property] = extension[property];
      } catch (warning) {
      }
    }
  }
 //Creating a new child
  function createChild () {
    return new child;
  }
 //Create child function . Root function
  function child () {console.log('child created')}
 //Prototype. Using .methods is not required.
  child.methods = child.prototype = {
    init: function () {
      return this;
    },
    test: function () {
      console.log('test');
      return this;
    }
  }
  //Extend existing functions methods.
  //Here we are adding a new method in object of child and adding test1.
  extendProperties(child.methods, {
    test1: function () {
      console.log('test1');
      return this;
    }
  })

//Achieving chaining.
createChild().test().test1()