Search code examples
javascriptprototype-programming

How to give prototype method access to parent variables?


I have a little library that can perform methods on a specific DOM element. It looks a little like this:

//An accessor method for the library
window.$ = function(selector){
    var new_instance = new lib();
    return new_instance.init(selector);
}
//And the actual library...
function lib(){
    this.context = window;
    this.init = function(sel){
        this.context = document.querySelector(sel);
        return this;
    };
    this.addPlugin = function(name, fn){
        lib.prototype[name] = fn;
        return this;
    };
}

Like Prototype or jQuery, you select the element with a $(_selector_) call. To add a method to the library, you would use the lib.addPlugin(...) method. Unfortunately, when I add a method like so:

lib.addPlugin('foo',function(){
    console.log(this.context);
    return this;
});

The THIS keyword refers to window, not the original parent library instance. I don't know much about how all the prototype stuff works, but I am wondering if there is someway I can get around/fix this. I would like newly added methods to be able to reference the parent library's variables.


Solution

  • Do not redefine functions in the constructor, you are creating a closure every time you call $, which uses a lot of memory.

    Anyways I didn't see any other problem other than addPlugin being an instance method instead of static method which I implemented like this:

    function lib(){
    this.context = window;
    }
    
    lib.addPlugin = function(name, fn){
      this.prototype[name] = fn;
      return this;
     };
    
    lib.prototype.init = function(sel){
    this.context = document.querySelector(sel);
    return this;
    };
    

    jsfiddle: http://jsfiddle.net/rAasm/