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) {  
    return new My_jquery(id);  
}  

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

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

$('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) {
  return new DOMNode(id);
}

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

DOMNode.prototype.insert = function(value) {

  if (value) {

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

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

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

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

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

Some play stuff:

<div id="d0">d0</div>
<div id="d1">d1</div>
<div id="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) {
  return new getDOM(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"