A description of function overloading in JavaScript
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 overloadingThe 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 examplefunction overload(a){ console.log('一个参数') } function overload(a,b){ console.log('两个参数') } // 在支持重载的编程语言中,比如 java overload(1); //一个参数 overload(1,2); //两个参数 // 在 JavaScript 中 overload(1); //两个参数 overload(1,2); //两个参数
function overload () { if (arguments.length === 1) { console.log('一个参数') } if (arguments.length === 2) { console.log('两个参数') } } overload(1); //一个参数 overload(1, 2); //两个参数
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"] };
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.
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); } } }
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
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
// 不传参数时,返回整个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="/static/imghw/default1.png" data-src="https://img.php.cn//upload/image/139/643/301/1531471079834608.jpg" class="lazy" 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="/static/imghw/default1.png" data-src="https://img.php.cn//upload/image/776/481/734/1531471070297469.png" class="lazy" 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 ); }
// 设置多个属性值 // 如果属性名(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 ) { ...... }
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
