Home Web Front-end JS Tutorial Solution to JS function overloading_javascript skills

Solution to JS function overloading_javascript skills

May 16, 2016 pm 04:48 PM
javascript js function overloading

In object-oriented programming, many languages ​​support function overloading, which can perform different operations based on the different number and type of parameters passed by the function. However, JS does not support it and requires us to do some extra small actions.
 
There is an interesting variable called arguments in the function execution context of JS. It stores all the parameters passed when the function is executed in the form of an array, even if the function definition does not define so many formal parameters. Another special feature is that compared with the Array type, the arguments variable has and has only one length attribute. Array methods, such as push, pop, etc., do not have it. It is just a "pseudo array": it has the length attribute and stores The array can be accessed using the array accessor [], and is read-only and not writable.

1. Overloading for different numbers of parameters
It should be clear here, just use the length attribute of the arguments function to judge.


Copy code The code is as follows:


2. Overloading of different types of parameters
For a dynamically typed language like JS, the arbitrary nature of variable declarations dilutes the strict variable types in the minds of developers importance (PS: It is also based on the ECMA system, and AS has introduced the mandatory type of variable declaration). Many unexpected BUGs are actually caused by this automatic conversion of variable types. In fact, JS provides a very accurate method for us to strictly detect the type of variables. The more common ones are the typeof method and the constructor attribute.

1. typeof variable returns the variable type

Copy code The code is as follows:

temp = "say"; //string
temp = 1; //number
temp = undefined; //undefined
temp = null; //object
temp = {}; //object
temp = []; //object
temp = true; //boolean
temp = function (){} //function
alert(typeof temp);

Through the above test, you can see that null, Object, and Array return object types, and the following method can solve this problem.

2.Constructor attribute detects variable type

Every object in JS has a constructor attribute, which is used to reference the function that constructs this object. The variable type can be detected by judging this reference.

Copy code The code is as follows:

temp = "say";
temp.constructor ==String; //true
temp= {};
temp.constructor == Object;//true
temp= [];
temp.constructor == Array;//true

Through the above test, it is easy to distinguish Array and Object type variables. Let's do a test on the custom object to see what happens.

Copy code The code is as follows:

//Custom object
function Ball() {}
//Instantiate an object
var basketBall = new Ball();
basketBall.constructor==Ball; //true

This shows that the constructor attribute is also applicable to custom objects.

After clarifying the application of the above two methods, let’s return to the simulation of JS function overloading. The following example is overloading based on parameter types.

Copy code The code is as follows:

function talk(msg){
var t = typeof msg;
if(t=="string"){
alert("It's a string");
}
else if(t=="number"){
alert("It's a number");
}
}
talk(10); //It's a string
talk("demo"); //It's a number

Attached is a very clever function that strictly detects parameter types and numbers:

Copy code The code is as follows:

//Strictly check a variable list based on the parameter list The type of
function strict( types, args ) {
//Make sure the number of parameters matches the type core
if ( types.length != args.length ) {
//If the length does not match , then an exception is thrown
                                                        throw "Invalid number of arguments. Expected " types.length ", received " args.length " instead."; 🎜> for ( var i = 0; i < args.length; i ) {
                                                                        using           using   with           use using using using         through   through ’ s using ’ ’s   through out through out through through through through through through through through through out through through’s' ‐ to ‐‐‐‐‐‐‐ and‐ for ( var i = 0; i < args.length; i ) {                                                                                      types[i] ) {
                throw "Invalid argument type. Expected "                                                 " >}

//Use of the above method
function doFunction(id,name){
//Detect the number and type of parameters
strict([Number,String],arguments);
..
}


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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to distinguish function overloading and rewriting in C++ How to distinguish function overloading and rewriting in C++ Apr 19, 2024 pm 04:21 PM

Function overloading allows functions with the same name but different signatures in a class, while function overriding occurs in a derived class when it overrides a function with the same signature in the base class, providing different behavior.

Overloading and rewriting of PHP functions Overloading and rewriting of PHP functions Apr 26, 2024 pm 05:12 PM

Function overloading and rewriting are supported in PHP to create flexible and reusable code. Function overloading: allows the creation of functions with the same name but different parameters, and calls the most appropriate function based on parameter matching. Function rewriting: Allow subclasses to define functions with the same name and override parent class methods. When subclass methods are called, they will override parent class methods.

How to implement function overloading in golang? How to implement function overloading in golang? Apr 29, 2024 pm 05:21 PM

The Go language does not support traditional function overloading, but similar effects can be achieved through the following methods: using named functions: creating unique names for functions with different parameters or return types; using generics (Go1.18 and above): creating unique names for different types of parameters A single version of the function.

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

Best practices for C++ function overloading Best practices for C++ function overloading Apr 20, 2024 am 10:48 AM

Best practices for C++ function overloading: 1. Use clear and meaningful names; 2. Avoid too many overloads; 3. Consider default parameters; 4. Keep the parameter order consistent; 5. Use SFINAE.

Does C++ function overloading apply to constructors and destructors? Does C++ function overloading apply to constructors and destructors? Apr 14, 2024 am 09:03 AM

C++ constructors support overloading, but destructors do not. Constructors can have different parameter lists, while destructors can only have an empty parameter list because it is automatically called when destroying a class instance without input parameters.

What are the application scenarios of C++ function overloading in actual projects? What are the application scenarios of C++ function overloading in actual projects? Apr 26, 2024 pm 01:57 PM

Function overloading allows functions with the same name to be defined differently in C++, handle different types of arguments, or perform different operations. Specific application scenarios include: processing different data types to provide different functions to improve code readability

See all articles