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!

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version
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.

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment
