简体   繁体   中英

How to define shorthand function in javascript

I'm wondering how to setup a shorthand function for a shorthand selector in javascript. I apologise if that isn't the correct termonolgy.

Example:

var abc = function (selector) {
  return document.querySelector(selector);
};

Allows you to:

var temp = abc('#someID').value;

What I'm wondering is how do you go about creating a custom .something (in a similar fashion to how jQuery have .val)?

For example calling:

abc('#someID').doSomething;

The the doSomething command allowing you to update the value (or pull it back) in a similar fashion to .val etc.

Thank you in advance.

To make that, you must return an object (easiest solution) or extend the prototype (advanced solution).

Returning an object

You can return the doSomething() method:

var abc = function (selector) {
  return {
        doSomething: function() {caller()},
        dom: document.querySelector(selector);
  }
};

And it works:

var temp = abc("#someID").dom.value;
var doSome = abc("#someID").doSomething();

Extending prototype

You can add a function to the object prototype:

var abc = function(sel){
     return document.querySelector(sel);
}
abc.prototype.doSomething = function() {
    caller();
};

And it works

var temp = new abc("#someID");
temp.doSomething(); //doSomething() method
temp.value; // value attribute of element

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.

  1. 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.
  2. 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/

Jquery keeps your selection in an internal property and decorates that property with methods that can help with is DOM presence.

Almost every time it returns the same object so you can chain method calls.

The point is that you cannot avoid keeping a reference to the selected DOM element and the decoration part

A simple example about selection and manipulating the DOM element note here i store a reference to document.querySelector and document.querySelectorAll which are pretty much as good as jquery selection mechanism (Sizzle)

var MyWrapper = (function(){
  var $ = document.querySelector.bind(document);
  var $$ = document.querySelectorAll.bind(document);
  var slice = Array.prototype.slice;
  var selection;

  var that = {
    select: select,
    remove: remove,
    html: html
  };

  function select(selector){
    selection = $(selector);
    return that;
  }

  function remove(){
    selection.parentNode.removeChild(selection);
    return undefined;
  }

  function html(htmlstring){
    if(typeof htmlstring == 'undefined'){
      return selection.innerHTML;
    } else {
      selection.innerHTML = htmlstring;
      return that;
    }
  }

  return that;
}())

of course jQuery is a much complex and sophisticated library for all kind of use cases but the above code can get you started

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM