Home > Web Front-end > JS Tutorial > A description of function overloading in JavaScript

A description of function overloading in JavaScript

不言
Release: 2018-07-13 16:38:41
Original
1596 people have browsed it

This article mainly introduces the instructions on function overloading in JavaScript, which has certain reference value. Now I share it with you. Friends in need can refer to it

Instructions

## There is no real function overloading in #JavaScript.

Function overloading

The function name is the same, but the parameter list of the function is different (including the number of parameters and parameter type), and different operations are performed according to the different parameters.

Let’s take an example

function overload(a){
    console.log('一个参数')
}

function overload(a,b){
    console.log('两个参数')
}

// 在支持重载的编程语言中,比如 java
overload(1);         //一个参数
overload(1,2);    //两个参数


// 在 JavaScript 中
overload(1);         //两个参数
overload(1,2);    //两个参数
Copy after login
In JavaScript, if two functions with the same name appear in the same scope, the latter one will overwrite the previous one, so there is no real significance in JavaScript. load.

But there are various ways to simulate the effect of overloading in JavaScript.

Let’s look at the first method first, which is implemented through the arguments object.

The arguments object is an array-like object inside the function. It stores all the parameters passed to the function when the function is called. .

function overload () {
  if (arguments.length === 1) {
    console.log('一个参数')
  }
  if (arguments.length === 2) {
    console.log('两个参数')
  }
}

overload(1);      //一个参数
overload(1, 2);  //两个参数
Copy after login
This example is very simple. It determines how many parameters there are by judging the length property of the arguments object, and then performs what operation.

But when there are few parameters, it is okay. If there are more parameters, the if judgment needs to be written a lot, which is troublesome.

So, let’s look at a classic example again

Before looking at this example, let’s first look at a requirement. We have a users object, and some names are stored in the values ​​attribute of the users object.
A name consists of two parts, the one on the left side of the space is first-name, and the one on the right side of the space is last-name, like below.

var users = {
  values: ["Dean Edwards", "Alex Russell", "Dean Tom"]
};
Copy after login
We need to add a find method to the users object.

When no parameters are passed, the entire

users.values is returned; When one parameter is passed When, the element whose first-name matches this parameter is returned;
When two parameters are passed, the element whose first-name and last-name both match are returned.

In this requirement, the find method needs to perform different operations according to the number of parameters. Next, we use an addMethod function to add the find method to the users object.

function addMethod (object, name, fn) {
  // 先把原来的object[name] 方法,保存在old中
  var old = object[name];

  // 重新定义 object[name] 方法
  object[name] = function () {
    // 如果函数需要的参数 和 实际传入的参数 的个数相同,就直接调用fn
    if (fn.length === arguments.length) {
      return fn.apply(this, arguments);

      // 如果不相同,判断old 是不是函数,
      // 如果是就调用old,也就是刚才保存的 object[name] 方法
    } else if (typeof old === "function") {
      return old.apply(this, arguments);
    }
  }
}
Copy after login
addMethod function, which receives 3 parameters

The first: the object to which the method is to be bound,
The second: the name of the bound method,
The third: required Binding method

When the addMethod function determines the number of parameters, in addition to using the arguments object, it also uses the length attribute of the function.

The length attribute of the function returns the number of formal parameters when the function was defined.

Simply put, the length of a function is how many parameters the function requires, and

arguments.length means how many parameters are really given to the function when calling the function

function fn (a, b) {
  console.log(arguments.length)
}
console.log(fn.length);  // 2
fn('a');    // 1
Copy after login
Let's use this addMethod function

// 不传参数时,返回整个values数组
function find0 () {
  return this.values;
}
// 传一个参数时,返回firstName匹配的数组元素
function find1 (firstName) {
  var ret = [];
  for (var i = 0; i The addMethod function takes advantage of the characteristics of closures and connects each function through the variable old, allowing all functions to stay in memory. <p></p>Every time the addMethod function is called, an old will be generated, forming a closure. <p>We can print the find method to the console through <br>console.dir(users.find)<code>. </code></p><p><img src="https://img.php.cn//upload/image/139/643/301/1531471079834608.jpg" title="1531471079834608.jpg" alt="A description of function overloading in JavaScript"></p>The above example was written by John Resig, the father of jQuery, on his blog and in the first edition of his book "Secrets of the JavaScript Ninja" As mentioned, Function overloading is also explained in Chapter 4 of the book. The addMethod function in the article is Example 4.15 in the book. Interested friends can take a look. <p></p>The above examples are essentially about judging the number of parameters and performing different operations based on the different numbers. The example below is about performing different operations by judging the type of parameters. <p></p>Let’s take a look at the css() method in jQuery. <h3></h3>css() method returns or sets one or more style properties of the matched element. <blockquote></blockquote><p>css(name|pro|[,val|fn])<code> </code></p><p><img src="https://img.php.cn//upload/image/776/481/734/1531471070297469.png" title="1531471070297469.png" alt="A description of function overloading in JavaScript"></p>We can see the css() method, there are There are 5 parameter situations, 3 of which are one parameter, and the other two are two parameters. <p>In the case of only one parameter, if the parameter type is a string or array, the attribute value is obtained, and if the parameter is an object, the attribute value is set. <br></p>jQuery’s css() method determines what operation to perform by judging the type of the parameter. <p></p>Let’s take a look at the source code in jQuery 3.3.1<p></p><pre class="brush:php;toolbar:false">// name 表示属性名
// value 表示属性值
css: function( name, value ) {
    return access( this, function( elem, name, value ) {
        var styles, len,
            map = {},
            i = 0;

        // 判断属性名是不是数组
        // 是数组就遍历,调用jQuery.css 方法传入每个属性名,获取样式
        if ( Array.isArray( name ) ) {
            styles = getStyles( elem );
            len = name.length;

            for ( ; i  1 );
}
Copy after login
css() method depends on three methods:

1, jQuery.access() method, this The method can get or set one or more attribute values
jQuery.access() method has such code

// 设置多个属性值
// 如果属性名(key)的类型是 object,就遍历这个对象
// 遍历一次就调用一次 access()方法,并传入这次的属性名和属性值
if ( jQuery.type( key ) === "object" ) {
    chainable = true;
    for ( i in key ) {
        jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
    }

// 设置一个值
} else if ( value !== undefined ) {
    ......
}
Copy after login
This is the method that helps the css() method to judge first Whether each parameter is a string or an object.

2. jQuery.style() method: Read or set style attributes on DOM nodes

In the css() method, if there is a second parameter passed, it means there are attributes to be set. value, the jQuery.style() method will be called to set the style

3. jQuery.css(): Read the DOM style value on the DOM element

Here jQuery.css( ) is a method added through jQuery.extend( ), and the css( ) method we mentioned at the beginning is a method added through jQuery.fn.extend( ), they Not the same method.

The difference between jQuery.extend() and jQuery.fn.extend()

jQuery.extend() is to add a class method (static method) to the jQuery class. It needs to be called through the jQuery class (directly using $.xxx);

jQuery.fn.extend() is to add members (instance methods) to the jQuery class, and all jQuery instances can be called directly (need to use $() .xxx call).

Benefits of overloading

Overloading actually merges multiple functions with similar functions into one function and reuses the function name.
If the css() method in jQuery does not use overloading, then there will be 5 different functions to complete the function. Then we need to remember 5 different function names and the parameters corresponding to each function. The number and type are obviously more troublesome.

Summary

Although JavaScript does not have overloading in the true sense, the effect of overloading is very common in JavaScript. For example, in the splice() method of an array, one parameter can be deleted, and two parameters can be deleted. Part of one parameter can be deleted, and three parameters can be deleted before adding new elements.
Another example is the parseInt() method. When a parameter is passed in, it will be judged whether to use hexadecimal parsing or decimal parsing. If two parameters are passed in, the second parameter will be used as the base of the number. parse.

The methods mentioned in the article to achieve overloading effects are essentially based on judging parameters. Whether it is judging the number of parameters or judging the parameter type, the operation is decided based on the different parameters. .

Although overloading can bring us a lot of convenience, it should not be abused. Don't combine some unrelated functions into one function. That is meaningless.

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

Analysis of js event bubbling and event capture

About how Ajax implements cross-domain Introduction to visit issues

The above is the detailed content of A description of function overloading in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template