viktor
viktor

Reputation: 1048

return a HTML element wrapped in a prototype type object javascript

if I want to return a HTML dom element wrapped in a prototype defined object in order to have access at the methods added to the prototype how would I go about it. A more concrete example of what I am trying to achieve is as follows:

(function(window, document, undefined) {

    var i;
    var el;

    var Dome = function(selector, getAllMatches) {
        return Dome.core.init(selector, getAllMatches);
    };

    Dome.core = Dome.prototype = {
        constructor: Dome,
        el: "",
        init: function(selector, getAllMatches) {

            if (typeof arguments[0] !== "undefined") {
               this.el = getElement(selector);
                       if (this.el instanceof Dome){
                          return this.el;
                       }

                       else{
                          return this.el;
                       }
            }
        }

    .....

})(window, document);

what I am trying to achieve is return instead of this.el an instanceof Dome so I can have access to it's methods. I know this is done very well by jquery but I do not have so much experience with js an near to 0 with prototype.

Upvotes: 1

Views: 178

Answers (1)

Simon
Simon

Reputation: 37978

Sounds like you want a Factory?

  function Dome(element){
    this.element = element;

    this.getElement = function(){
      return this.element;
    }
  }

  Dome.factory = function(selector){
      var el = getElement(selector);
      return new Dome(el);
  }

  var d = Dome.factory('test');
  alert(d.getElement());

+Edit+

Since you asked about how jQuery does it, I just took a quick look...

So the main jQuery factory ($, jQuery) is;

jQuery = function( selector, context ) {
    // The jQuery object is actually just the init constructor 'enhanced'
    return new jQuery.fn.init( selector, context, rootjQuery );
}

Then later, jQuery.fn.init has it's prototype populated from jQuery.fn.

So editing my original answer to match this format would be;

  function Dome(element){
    this.element = element;
  }

  Dome.core = {
    getElement: function(){
      return this.element;
    }
  };

  Dome.prototype = Dome.core;

  Dome.factory = function(selector){
      var el = getElement(selector);
      return new Dome(el);
  }

  var d = Dome.factory('test');
  alert(d.getElement());

Upvotes: 1

Related Questions