简体   繁体   English

如何在javascript中定义速记函数

[英]How to define shorthand function in javascript

I'm wondering how to setup a shorthand function for a shorthand selector in javascript. 我想知道如何在javascript中为速记选择器设置速记函数。 I apologise if that isn't the correct termonolgy. 如果那不是正确的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)? 我想知道的是你如何创建一个自定义.something(以类似于jQuery的方式.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. doSomething命令允许您以与.val等类似的方式更新值(或将其拉回)。

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: 您可以返回doSomething()方法:

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. 嗯,这是一个非常好的JS代码设计问题。

Let's try to create a simple jQuery implementation. 让我们尝试创建一个简单的jQuery实现。 For this, we should first scope things up. 为此,我们首先要做好准备。

  1. jQuery function is a wrapper. jQuery函数是一个包装器。 It will hold a reference to the node in the DOM, and it will provide an array functions that will "operate" on the node. 它将保存对DOM中节点的引用,它将提供将在节点上“操作”的数组函数。
  2. Most of the functions (setters, for being more specific) should return a pointer to the wrapper itself, so you can chain operations. 大多数函数(setter,更具体)应返回一个指向包装器本身的指针,因此您可以链接操作。

You can define the wapper first, by defining your function. 您可以通过定义函数来首先定义wapper。

// 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/ 见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. Jquery将您的选择保留在内部属性中,并使用可以帮助DOM存在的方法来装饰该属性。

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 关键是你无法避免保留对所选DOM元素和装饰部分的引用

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) 关于选择和操作DOM元素的一个简单示例请注意这里我存储了对document.querySelectordocument.querySelectorAll的引用,这些引用与jquery选择机制(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 当然,jQuery是一个非常复杂和复杂的库,适用于所有类型的用例,但上面的代码可以帮助您入门

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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