Skip to content Skip to sidebar Skip to footer

How To Use Prototype For Custom Methods And Object Manipulation

Honestly, I am trying to understand JavaScript prototypes and I'm not making much progress. I am not exactly sure how to explain what I am trying to do, except to say that in part

Solution 1:

var $ = function(id) {  
    returnnewMy_jquery(id);  
}  

functionMy_jquery(id) { 
    this.elem = document.getElementById(id);
}

My_jquery.prototype = {
   insert : function(text) { this.elem.innerHtml = text; returnthis;}
}

$('para1').insert('hello world').insert('chaining works too');  

add any method u want to operate on elem in My_jquery.prototype

Solution 2:

You can use a scheme like the following:

function$(id) {
  returnnewDOMNode(id);
}

functionDOMNode(id) {
  this.element = document.getElementById(id);
}

DOMNode.prototype.insert = function(value) {

  if (value) {

    // If value is a string, assume its markupif (typeof value == 'string') {
      this.element.innerHTML = value;

    // Otherwise assume it's an object
    } else {

      // If it's a DOM objectif (typeof value.nodeName == 'string') {
        this.element.appendChild(value);

      // If it's a DOMNode object
      } elseif (this.constructor == DOMNode) {
        this.element.appendChild(value.element);
      }
    }
  } // If all fails, do nothing
}

$('id').insert('foo bar');

Some play stuff:

<divid="d0">d0</div><divid="d1">d1</div><divid="d2">d2</div><script>// insert (replace content with) string, may or may not be HTML
$('d0').insert('<b>foo bar</b>');

// insert DOMNode object
$('d0').insert($('d1'));

// Insert DOM element
$('d0').insert(document.getElementById('d2'));

</script>

You may find it useful to study how MyLibrary works, it has some very good practices and patterns.

Solution 3:

Try this.

var getDOM= function(id) {
  this.element= document.getElementById(id);
}

getDOM.prototype.insert= function(content) {
  this.element.innerHTML= content;
}

var $= function(id) {
  returnnewgetDOM(id);
};

$('id').insert('Hello World!'); // can now insert 'Hello World!' into document.getElementById('id')

Post a Comment for "How To Use Prototype For Custom Methods And Object Manipulation"