2

I'm wanting to develop a library following some interesting patterns of jQuery (Builder and Prototype, basically). I tried to read the jQuery source and search for tutorials but did not get anywhere.

My idea is to allow access of this type:

  • grace(...) is callable directly
  • grace.set(...) can have methods
  • grace.fn.get = ... can set new methods

The most I got was this:

(function(window, undefined) {

    "use strict";

    //
    var grace = function(options) {
        return new grace.fn.init(options);
    };

    //
    grace.fn = grace.prototype = {
        //
        set: function() {
            alert("grace.set() OK");
        },

        //
        init: function() {
            alert("grace() OK");
        },
    };

    //
    window.grace = grace;

})(window);

It is callable directly, but their methods are not accessible.

3
  • 2
    Copy all grace.fn properties to the grace Commented Dec 19, 2013 at 4:15
  • jsfiddle.net/J825H/1 Commented Dec 19, 2013 at 4:21
  • window.grace = grace.fn; jsfiddle.net/J825H/2 Commented Dec 19, 2013 at 4:23

1 Answer 1

2

An extend method is supposed to add to grace and grance.fn, and when you want to add new methods to grace, use grace.extend; when you want to add new methods to instances that grace() creates, use grace.fn.extend. Take a look at code below:

(function(window, undefined) {
   "use strict";

    var grace = function(options) {
        return new grace.fn.init(options);
    };

    grace.fn = grace.prototype = {
        init: function() {
            alert("grace() OK");
        },
    };

    grace.extend = grace.fn.extend = function() {/* code here */}

    grace.extend({ // add new methods to grace itself
        set: function() {
            alert("grace.set() OK");
        }
    })

    grace.fn.extend({
       /* add new methods to instances that grace() creates */
    })

    grace.fn.init.prototype = grance.fn;
    window.grace = grace;

})(window);

Note: grace.fn.init.prototype = grance.fn is needed because new grace.fn.init(options) will get an object inherits methods from grace.init.prototype. Without that line of code, you won't get these methods of grace.fn.

Sorry for my poor english, and sorry for not having runnable code. Hope code above will inspire you.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.