ES6 series four: function extension

Time:2021-4-27

The rookie official account of “Code tailor” provides technical information and a series of basic articles for front-end developers. WeChat pays close attention to the public address of “little and mountain rookie”, and gets the latest articles in time.

preface

Before learning, we would like to tell you that this article is an introduction to ecmascript6 by Ruan Yifeng“Extension of functionIf you have mastered the following knowledge items, you can skip this link and go directly to the exercise

  • Default values for function arguments
  • Scope
  • Rest parameter
  • Arrow function

If you forget something, it’s ready for you!

Learning links

Extended learning of functions

Summary

Default values for function arguments

Specify default values for the parameters of the function

//Es5 writing
function log(x, y) {
  y = y || 'World'
  console.log(x, y)
}

log('Hello') // Hello World

//ES6 writing
function log(x, y = 'World') {
  console.log(x, y)
}

log('Hello') // Hello World

advantage:

  • People who read the code can immediately realize which parameters can be omitted without looking at the function body or the document
  • It is conducive to future code optimization. Even if this parameter is completely removed in the external interface of the future version, the previous code will not be unable to run

be careful:

  • Parameter variables are declared by default, so they cannot be usedletorconstAgain
function foo(x = 5) {
  let x = 1 // error
  const x = 2 // error
}
  • When using parameter defaults, functions cannot have parameters with the same name
//No error
function foo(x, x, y) {
  // ...
}

//Error report
function foo(x, x, y = 1) {
  // ...
}
  • The parameter default value is not passed, but the value of the default value expression is recalculated every time. In other words, the default value of the parameter is lazy
let x = 99
function foo(p = x + 1) {
  console.log(p)
}

foo() // 100

x = 100
foo() // 101

Scope

Once the default value of the parameter is set, the parameter will form a separate context when the function is declared and initialized. When initialization is complete, the scope disappears. This kind of syntax behavior will not appear when the parameter default value is not set.

var x = 1
function foo(
  x,
  y = function () {
    x = 2
  },
) {
  var x = 3
  y()
  console.log(x)
}

foo() // 3
x // 1

//Dividing line

var x = 1
function foo(
  x,
  y = function () {
    x = 2
  },
) {
  x = 3
  y()
  console.log(x)
}

foo() // 2
x // 1

Rest parameter

ES6 introductionrestParameter (in the form of… Variable name), which is used to obtain redundant parameters of the function, so that it is unnecessary to useargumentsIt’s not the right person.restThe parameter matching variable is an array, which puts the redundant parameters into the array.

function add(...values) {
  let sum = 0

  for (var val of values) {
    sum += val
  }

  return sum
}

add(2, 5, 3) // 10

//The add function in the above code is a summation function, which can be added to by using the rest parameter
//Pass in any number of parameters.

be careful,restThere can be no other parameters (that is, only the last parameter) after the parameter, otherwise an error will be reported.

Arrow function

ES6 allows arrow(=>)Define the function.

var f = (v) => v

//Equivalent to
var f = function (v) {
  return v
}

If the arrow function does not require parameters or requires multiple parameters, a bracket is used to represent the parameter part.

var f = () => 5
//Equivalent to
var f = function () {
  return 5
}

var sum = (num1, num2) => num1 + num2
//Equivalent to
var sum = function (num1, num2) {
  return num1 + num2
}

If the code block part of the arrow function has more than one statement, use curly braces to enclose them, and use thereturnStatement.

var sum = (num1, num2) => {
  return num1 + num2
}

The arrow function has several points for attention

  • In function bodythisObject is the object in which it is defined, not used.
  • It can’t be used as a constructor, that is, it can’t be usednewCommand, otherwise an error is thrown.
  • It can’t be usedargumentsObject that does not exist in the body of the function. If you want to use it, you can use itrestParameter substitution.
  • It can’t be usedyieldCommand, so the arrow function cannot be used as aGeneratorFunction.

Of the above four points, the first is particularly noteworthy.thisThe direction of the object is variable, but in the arrow function, it is fixed.

Topic self test

1: What does the following code output

var x = 1
function foo(x, y = () => (x = 5)) {
  x = 9
  y()
  console.log(x)
}

foo()

2: What does the following code output

const shape = {
  radius: 10,
  diameter() {
    return this.radius * 2
  },
  perimeter: () => 2 * Math.PI * this.radius,
}

shape.diameter()
shape.perimeter()
  • A: 20 and 62.83185307179586
  • B: 20 and NaN
  • C: 20 and 63
  • D: NaN and 63

3: Explain the following code (meaning, running result and function).

f1 = (x) => (y) => (z) => x * y * z

Topic analysis

1

Answer:5

First you need to understand the functionfoofunction foo(x, y = () => x = 5)The focus is on the secondy = () => x = 5Need to givefooFunction a function, if not, then y stands for

;() => {
  x = 5
}

This function is called herefooIt doesn’t give the second function, so when it’s executed,y()In fact, it’s about puttingxAssign to5So print it out as5


2

Answer:B

First of all, you need to understand that in the arrow function,thisThe direction of the arrow function is different from that in the ordinary functionthisThe point is defined. staydiameterFunction, through thethis.radiusWhat I visited wasshapeInradius, for10

But, inperimeterFunction, followed bythis.radiusVisitedradiusNot at allshapeInradius, found in the outer layer, so returnedNaN. So the answer is20 and NaN


3

First of all, the logic of using arrow function in this way is not very clear, so it is converted to ordinary function

function f1(x) {
  return function f2(y) {
    return function f3(z) {
      return x * y * z
    }
  }
}

Meaning: multiply three numbers

Results of operation:f1(x)(y)(z)===x*y*z

The outermost layer,f1Is a function with one parameter, and the return value is a function with one parameterf2,f1(x)(y)(z)->f2(y)(z),f2The return value is a function with one parameterf3,f2(y)(z)->f3(z)Because the returned function is in thef1andf2According to the scope chain, thexandySof3The return value of isx*y*zAnd finallyf1(x)(y)(z)===x*y*z

This is the end of ES 6 series function extension. Thank you for your support! Your attention and praise will be the strongest driving force for us to move forward! Thank you!