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); //两个参数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); //两个参数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"] };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.
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); } } }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
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'); // 1Let'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="/static/imghwm/default1.png" data-src="https://img.php.cn//upload/image/139/643/301/1531471079834608.jpg?x-oss-process=image/resize,p_40" 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/imghwm/default1.png" data-src="https://img.php.cn//upload/image/776/481/734/1531471070297469.png?x-oss-process=image/resize,p_40" 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 ); }css() method depends on three methods: 1, jQuery.access() method, this The method can get or set one or more attribute valuesjQuery.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 ) { ...... }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!

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base


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

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft