


How to operate the default parameters of processing functions in ES5 and ES6 environments
This time I will show you how to operate the default parameters of the processing function in the ES5 and ES6 environments. What are the precautions for operating the default parameters of the processing functions in the ES5 and ES6 environments. The following is a practical case, let's take a look. take a look.
The default value of the function is something that greatly improves the robustness (that is, it makes the program more robust) MDN's description of the default parameters of the function: The default parameter of the function allows to be passed without a value or undefined Use the default parameters when entering.ES5
Use logical OR || to achieve
As we all know, in the ES5 version, there is no direct method for us to deal with the default value of the functionSo we can only enhance the function of the function ourselves, which is usually done like this:
function doSomething (name, age) { name = name || 'default name' age = age || 18 console.log(name, age) }
uses the default value.
After executing the function, there seems to be nothing wrong:doSomething() // default name, 18 doSomething('Niko') // Niko , 18 doSomething(, 12) // default name, 12
doSomething('Niko', 0) // Niko, 18
console.log(0 || 'wrong') console.log('' || 'wrong') console.log(null || 'wrong') console.log(false || 'wrong')
Correct posture
So, the correct default value processing in ES5 should be like this:function doSomething (name, age) { if (name === undefined) { name = 'default name' } if (age === undefined) { age = 18 } console.log(name, age) }
ternary operator operator to simplify the operation
Or we can shorten it to the ternary operator form:function doSomething (name, age) { name = name === undefined ? 'default name' : name age = age === undefined ? 18 : age console.log(name, age) }
Use functions for encapsulation
But if we have to repeat these operations every time we write a functionIt would be too troublesome, so we This logic is simply encapsulated:
function defaultValue (val, defaultVal) { return val === undefined ? defaultVal : val } function doSomething (name, age) { name = defaultValue(name, 'default name') age = defaultValue(age , 18) console.log(name, age) }
we can use this method to save the operation of the ternary operator:
function defaultValue () { return arguments[+(arguments[0] === undefined)] }
ES6
The default value of the function in the ES6 version is basically the routine we implemented aboveBut because It is native, so there will be corresponding new syntax, which can be used more concisely:function doSomething (name = 'default name', age = 18) { console.log(name, age) }
Using this method directly eliminates the need to check the default value inside the function, allowing the function to focus on doing what it should do.
How to throw exceptions for certain required parameters
This new syntax of ES6 allows us to Error reminder for a required parameter:function requireParams () { throw new Error('required params') } function doSomething (name = requireParams(), age = 18) { // do something }
Default value processing of complex structure parameters
The above processing is for simple basic type data, but if we There is a function as follows:function init ({id, value}) {} init({ id: 'tagId', value: 1 })
如果在ES5环境下,针对这种参数的默认值处理将会变得无比复杂
首先要判断这一个参数是否存在,然后在判断参数中的所有key是否存在
而在ES6中,可以这样来做:
function init ({ id = 'defaultId', value = 1 } = {}) { console.log(id, value) } init()
首先在解构函数的后边添加默认值= {},然后针对每一项参数添加默认值,很简洁的就实现了我们的需求。
ES5版本的polyfill代码在仓库中的位置:defaultValue
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of How to operate the default parameters of processing functions in ES5 and ES6 environments. 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

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

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

Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

The key to writing efficient and maintainable Java functions is: keep it simple. Use meaningful naming. Handle special situations. Use appropriate visibility.

The advantages of default parameters in C++ functions include simplifying calls, enhancing readability, and avoiding errors. The disadvantages are limited flexibility and naming restrictions. Advantages of variadic parameters include unlimited flexibility and dynamic binding. Disadvantages include greater complexity, implicit type conversions, and difficulty in debugging.

The benefits of functions returning reference types in C++ include: Performance improvements: Passing by reference avoids object copying, thus saving memory and time. Direct modification: The caller can directly modify the returned reference object without reassigning it. Code simplicity: Passing by reference simplifies the code and requires no additional assignment operations.

The difference between custom PHP functions and predefined functions is: Scope: Custom functions are limited to the scope of their definition, while predefined functions are accessible throughout the script. How to define: Custom functions are defined using the function keyword, while predefined functions are defined by the PHP kernel. Parameter passing: Custom functions receive parameters, while predefined functions may not require parameters. Extensibility: Custom functions can be created as needed, while predefined functions are built-in and cannot be modified.

Exception handling in C++ can be enhanced through custom exception classes that provide specific error messages, contextual information, and perform custom actions based on the error type. Define an exception class inherited from std::exception to provide specific error information. Use the throw keyword to throw a custom exception. Use dynamic_cast in a try-catch block to convert the caught exception to a custom exception type. In the actual case, the open_file function throws a FileNotFoundException exception. Catching and handling the exception can provide a more specific error message.
