Home  >  Article  >  Web Front-end  >  How to operate the default parameters of processing functions in ES5 and ES6 environments

How to operate the default parameters of processing functions in ES5 and ES6 environments

php中世界最好的语言
php中世界最好的语言Original
2018-05-30 10:50:541458browse

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 function

So 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)
}
We will The two parameters name and age are processed as default values. If not,

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
However, when we execute such code, we will get some unexpected results:

doSomething('Niko', 0) // Niko, 18
It can be found that for parameter 0, our default parameter implementation method above is problematic.

Just like the four

expressions below, they will all output wrong, which obviously cannot satisfy the above requirements. MDN’s definition of function default parameters:

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)
}
Use the

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 function

It 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)
}
In this way, the logic of the default parameters of the function is very concisely implemented in ES5

one momre things

About the implementation of the defaultValue function above Method, after we reasonably use the advantages of weakly typed languages

we can use this method to save the operation of the ternary operator:

function defaultValue () {
 return arguments[+(arguments[0] === undefined)]
}
We know that arguments represent all the actual parameters of the function

We use arguments[0] to get the first actual parameter, and then perform a congruent comparison with undefined

Convert the result of the expression to Number in the outer layer, and then use this value as a subscript to get arguments corresponding parameters.

Because it is converted from Boolean value, there are only two options: 0 and 1.

This also realizes the function of the ternary operator above.

ES6

The default value of the function in the ES6 version is basically the routine we implemented above

But 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)
}
ES6 provides a new syntax that allows us to write = [defaultValue] directly after the function declaration parameters. form to set the default value of a parameter.

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
}
If the name parameter is undefined, the default value rule will be triggered

Then the requireParams function is called, and we directly throw one in the function Error

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中文网其它相关文章!

推荐阅读:

怎样优化js async函数

如何使用node搭建服务器,写接口,调接口,跨域

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!

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