Well, this is a very nice JS code-design question.
Let's try to create a simple jQuery implementation. For this, we should first scope things up.
- jQuery function is a wrapper. It will hold a reference to the node in the DOM, and it will provide an array functions that will "operate" on the node.
- Most of the functions (setters, for being more specific) should return a pointer to the wrapper itself, so you can chain operations.
You can define the wapper first, by defining your function.
// Here we define the constructor.
var q = function(selector){
this._node = document.querySelector(selector);
// Add more private stuff here if you like
};
//Now we can add functionality to the function prototype.
q.prototype.hide = function(){
this._node.style.visibility = 'hidden';
return this;
};
q.prototype.show = function(){
this._node.style.visibility = 'visible';
return this;
};
q.prototype.val = function(){
return this._node.value;
};
q.prototype.click = function(callback){
this._node.onclick = callback;
return this;
};
// This is just for not having to call new every-time we want a new instance
var $q = function(selector){
return new q(selector);
};
Now let's play a bit
<label for="name"> Hey I'm a text box</label>
<input id="name" value="" />
<button id="clickMe"> Click me </button>
We will attach a click handler to the button, when the user clicks, we display the value that the textbox contains, then we hide the text box. All in a single line (chained commands).
$q('#clickMe').click(function(){
alert($q('#name').hide().val());
});
See JsFiddle https://jsfiddle.net/4Lfangj4/