search
HomeWeb Front-endJS TutorialSolution to JS function overloading_javascript skills

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                                                                         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                 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
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
Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

See all articles

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

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool