Knowledge of ES6

Because many developers do not understand the relationship between language and platform, and ES related materials on the market are scattered, and we developers have different understanding and mastery of ES, which will be used in the subsequent trend of big front-end and advanced courses, so it is very important to learn ES. If you smell new ES6 features in a subsequent interview, please refer to the following information. Specific knowledge is as follows:

  1. ECMAScript Overview: JS is an extension of ECMAScript that implements its standard and extends it to ensure that it can be used in real projects. In the browser environment: js equals ES+WebAPI (DOM+BOM) in the Node environment: JS equals ES+ Node API (fs+net+etc..)
  2. ES2015
  • A. Solve the problems and shortcomings of the original grammar
  • B. Enhance the original syntax
  • C. Brand new objects, methods, and functions
  • D. Entirely new data types and data structures
  1. Let and block-level scope
/ / let's statement will only being declared in the block effect -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
if (true) {
  // var foo = 'zce'
  let foo = 'zce'
  console.log(foo)
}
/ / let's performance in the for loop -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -

for (var i = 0; i < 3; i++) {
  for (var i = 0; i < 3; i++) {
    console.log(i)
  }
  console.log('Inner end I =' + i)
}

for (var i = 0; i < 3; i++) {
  for (let i = 0; i < 3; i++) {
    console.log(i)
  }
  console.log('Inner end I =' + i)
}

/ / let application scenarios: loop binding event, the event handler gets right index -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --

var elements = [{}, {}, {}]
for (var i = 0; i < elements.length; i++) {
  elements[i].onclick = function () {
    console.log(i)
  }
}
elements[2].onclick()

var elements = [{}, {}, {}]
for (var i = 0; i < elements.length; i++) {
  elements[i].onclick = (function (i) {
    return function () {
      console.log(i)
    }
  })(i)
}
elements[0].onclick()

var elements = [{}, {}, {}]
for (let i = 0; i < elements.length; i++) {
  elements[i].onclick = function () {
    console.log(i)
  }
}
elements[0].onclick()

/ / a for loop will produce two layers of scope -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --

for (let i = 0; i < 3; i++) {
  let i = 'foo'
  console.log(i)
}

let i = 0

if (i < 3) {
  let i = 'foo'
  console.log(i)
}
i++

if (i < 3) {
  let i = 'foo'
  console.log(i)
}

i++

if (i < 3) {
  let i = 'foo'
  console.log(i)
}

i++


/ / let repaired the variable declarations ascending phenomenon -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --

console.log(foo)
var foo = 'zce'

console.log(foo)
let foo = 'zce'

Copy the code
  • A. The scope enclosed by curly braces is called the block-level scope
  • B. Variables declared by let are block-scoped variables and cannot be accessed externally
  • C. Let does not have the problem of declaration promotion
  1. const
  • A. Const cannot be modified after being declared
const name = 'zce'
// reassignment is not allowed after a constant has been declared
name = 'jack'

// Constant requires simultaneous assignment
const name
name = 'zce'

// The constant only requires that the inner direction not be allowed to be modified
const obj = {}
// There is no problem modifying the data members
obj.name = 'zce'

obj = {}

Copy the code

Best practice: Use const instead of var, with let 5. Array deconstruction

// Array destruct

const arr = [100.200.300]

const foo = arr[0]
const bar = arr[1]
const baz = arr[2]
console.log(foo, bar, baz)

const [foo, bar, baz] = arr
console.log(foo, bar, baz)

const [, , baz] = arr
console.log(baz)

const [foo, ...rest] = arr
console.log(rest)

const [foo, bar, baz, more] = arr
console.log(more)

const [foo, bar, baz = 123, more = 'default value'] = arr
console.log(bar, more)

const path = '/foo/bar/baz'
// const tmp = path.split('/')
// const rootdir = tmp[1]

const [, rootdir] = path.split('/')
console.log(rootdir)

Copy the code
  • B. Use […rest] to get all values following the current element
  1. Object deconstruction
  • Const {name} = obj const {name} = obj
  • B. Other uses are the same as arrays
// Object deconstruction

const obj = { name: 'zce'.age: 18 }

const { name } = obj
console.log(name)

const name = 'tom'
const { name: objName } = obj
console.log(objName)

const name = 'tom'
const { name: objName = 'jack' } = obj
console.log(objName)

const { log } = console
log('foo')
log('bar')
log('123')

Copy the code
  1. Template string
  • A. Use back quotation marks
  • B. byhey, ${name}This way you can add the name variable directly to the string
  • C. You can define label functions to process template strings
// Template string

// backquotes wrap
const str = `hello es2015, this is a string`

// Line breaks are allowed
const str = `hello es2015, this is a \`string\``

console.log(str)

const name = 'tom'
// You can insert an expression with ${}, and the result of the expression will be printed to the corresponding location
const msg = `hey, ${name} --- The ${1 + 2} ---- The ${Math.random()}`
console.log(msg)

// Tagged template string

// The template string tag is a special function,
// Use this tag to call this function
// const str = console.log`hello world`

const name = 'tom'
const gender = false

function myTagFunc (strings, name, gender) {
  // console.log(strings, name, gender)
  // return '123'
  const sex = gender ? 'man' : 'woman'
  return strings[0] + name + strings[1] + sex + strings[2]}const result = myTagFunc`hey, ${name} is a ${gender}. `

console.log(result)

Copy the code
  1. String extension methods
  • A. startsWith() what does the string start with
  • B. incluses(
  • C. endsWith(
// String extension methods

const message = 'Error: foo is not defined.'

console.log(
  // message.startsWith('Error')
  // message.endsWith('.')
  message.includes('foo'))Copy the code
  1. Parameter Default Value
  • A. The default value is followed by a direct argument, and the parameter with the default value is placed last
// Default values for function arguments

function foo (enable) {
  // Short-circuit operations are not suitable for default arguments in many cases, such as 0 "false null
  // enable = enable || true
  enable = enable === undefined ? true : enable
  console.log('foo invoked - enable: ')
  console.log(enable)
}

The default parameter must be at the end of the parameter list
function foo (enable = true) {
  console.log('foo invoked - enable: ')
  console.log(enable)
}

foo(false)

Copy the code
  1. The remaining parameters
  • A. Arguments can be used directly in ES6. Args is defined this way. It can only be used once in the last digit.
// Remaining parameters

// function foo () {
// console.log(arguments)
// }

function foo (first, ... args) {
  console.log(args)
}

foo(1.2.3.4)
Copy the code
  1. The array a
  • A. Pass the first argument to this by apply, and the second is the array to expand
  • B. Also through… Is directly expanded
// Expand the array parameters
const arr = ['foo'.'bar'.'baz']

console.log(
  arr[0],
  arr[1],
  arr[2],)console.log.apply(console, arr)
console.log(... arr)Copy the code
  1. Arrow function
  • A. Use => to create a function
// Arrow function

// function inc (number) {
// return number + 1
// }

// The simplest way
// const inc = n => n + 1

// Complete argument list, function body multiple statements, return value still need to return
const inc = (n, m) = > {
  console.log('inc invoked')
  return n + 1
}

console.log(inc(100))

const arr = [1.2.3.4.5.6.7]

// arr.filter(function (item) {
// return item % 2
// })

// Common scenario, callback function
arr.filter(i= > i % 2)
Copy the code
  • B. The arrow function does not change the direction of this
  • C. This in the arrow function refers to this in the current scope
// Arrow function with this
// The arrow function does not change the this pointer

const person = {
  name: 'tom'.// sayHi: function () {
  // console.log(`hi, my name is ${this.name}`)
  // }
  sayHi: () = > {
    console.log(`hi, my name is The ${this.name}`)},sayHiAsync: function () {
    // const _this = this
    // setTimeout(function () {
    // console.log(_this.name)
    // }, 1000)

    console.log(this)
    setTimeout(() = > {
      // console.log(this.name)
      console.log(this)},1000)
  }
}

person.sayHiAsync()
Copy the code
  1. Enhancements to object literals
  • A. The calculated attribute name is wrapped in []
// Object literals

const bar = '345'

const obj = {
  foo: 123.// bar: bar
  // The attribute name is the same as the variable name, and can be omitted: bar
  bar,
  // method1: function () {
  // console.log('method111')
  // }
  // The method can be omitted: function
  method1 () {
    console.log('method111')
    // This method is a normal function, which also affects this pointing.
    console.log(this)},Math.random(): 123 // not allowed
  // Use [] to make the result of the expression the attribute name
  [bar]: 123
}

// obj[Math.random()] = 123

console.log(obj)
obj.method1()
Copy the code
  1. Object adding method
  • A. Assign overwrites the attributes of the target object with attributes from the following objects
  • B. is determines whether it is equal
  • c. definePropProperty
// Application scenario

function func (obj) {
  // obj.name = 'func obj'
  // console.log(obj)

  const funcObj = Object.assign({}, obj)
  funcObj.name = 'func obj'
  console.log(funcObj)
}

const obj = { name: 'global obj' }

func(obj)
console.log(obj)
Copy the code
  1. proxy
  • A. A proxy is equivalent to a gatekeeper, monitoring the access, reading and setting of objects
  • B. It contains get and set methods

/ / Proxy objects

const person = {
  name: 'zce'.age: 20
}

const personProxy = new Proxy(person, {
  // Monitor property reads
  get (target, property) {
    return property in target ? target[property] : 'default'
    // console.log(target, property)
    // return 100
  },
  // Monitor property Settings
  set (target, property, value) {
    if (property === 'age') {
      if (!Number.isInteger(value)) {
        throw new TypeError(`${value} is not an int`)
      }
    }

    target[property] = value
    // console.log(target, property, value)}})Copy the code

c. 16. Reflect

  • A. Static classes that encapsulate a series of low-level operations on objects
/ / Reflect object

const obj = {
  foo: '123'.bar: '456'
}

const proxy = new Proxy(obj, {
  get (target, property) {
    console.log('watch logic~')
    
    return Reflect.get(target, property)
  }
})

console.log(proxy.foo)

const obj = {
  name: 'zce'.age: 18
}

// console.log('name' in obj)
// console.log(delete obj['age'])
// console.log(Object.keys(obj))

console.log(Reflect.has(obj, 'name'))
console.log(Reflect.deleteProperty(obj, 'age'))
console.log(Reflect.ownKeys(obj))
Copy the code
  1. Promise
  • A. New asynchronous programming solution
  1. class
  • A. Syntax for independent declaration types
class Person {
  constructor (name) {
    this.name = name
  }
  say () {
    console.log(`hi, my name is The ${this.name}`)}}const p = new Person('tom')
p.say()
Copy the code
  1. Class inheritance
/ / extends to inherit

class Person {
  constructor (name) {
    this.name = name
  }

  say () {
    console.log(`hi, my name is The ${this.name}`)}}class Student extends Person {
  constructor (name, number) {
    super(name) // Parent constructor
    this.number = number
  }

  hello () {
    super.say() // Call the parent member
    console.log(`my school number is The ${this.number}`)}}const s = new Student('jack'.'100')
s.hello()

Copy the code
  1. New set data structure
  • A. Very similar to arrays, except that set members are not allowed to duplicate each other
  • B. It contains the has method to determine whether a certain value exists in the set
  1. Map data structure
    • A. Strictly a collection of key-value pairs, much like objects, that can be of any type
  1. Symbol
  • A. New data type that defines a unique value
  • B. Use it on the keys of objects to avoid duplicate keys
  • C. Use it on a private member of an object to prevent external access to the member
  • D. A string Symbol can be passed through symbol.for (” “). Two symbols of the same Symbol have the same value. But the value passed in is automatically converted to a string, and the Boolean true passed in returns the same value as the string true
  1. for of
  • A. Loop can be terminated with break
  • B. Set can be traversed
  • C. Traversing the map yields an array of two members
// for... Of circulation

const arr = [100.200.300.400]

for (const item of arr) {
  console.log(item)
}

// for... The of loop can replace the forEach method of an array object

arr.forEach(item= > {
  console.log(item)
})

for (const item of arr) {
  console.log(item)
  if (item > 100) {
    break}}Copy the code
  1. Iterable interface
  • A. for b. for C. for D. for
  • B. All data types that can be iterated over need to implement this Iterable, with an iterator method mounted inside
// An Iterator is an Iterator.

const set = new Set(['foo'.'bar'.'baz'])

const iterator = set[Symbol.iterator]()

// console.log(iterator.next())
// console.log(iterator.next())
// console.log(iterator.next())
// console.log(iterator.next())
// console.log(iterator.next())

while (true) {
  const current = iterator.next()
  if (current.done) {
    break // The iteration is over, there is no need to continue
  }
  console.log(current.value)
}
Copy the code
  1. The generator
  • A. The yeild function will not be executed directly, but will be executed by calling the next method
  • B. The generator object is automatically returned and the execution stops when the yeild value is encountered
  • C. Call next again to continue execution
  • D. Lazy execution
  1. Examples of generator functions
  • A. send number
/ / the Generator applications

// Case 1: signal transmitter

function * createIdMaker () {
  let id = 1
  while (true) {
    yield id++
  }
}

const idMaker = createIdMaker()

console.log(idMaker.next().value)
console.log(idMaker.next().value)
console.log(idMaker.next().value)
console.log(idMaker.next().value)

// Case 2: Implement the iterator method using a Generator function

const todos = {
  life: ['eat'.'sleep'.'Beat the beans'].learn: ['Chinese'.'mathematics'.'foreign language'].work: ['tea'],
  [Symbol.iterator]: function * () {
    const all = [...this.life, ...this.learn, ...this.work]
    for (const item of all) {
      yield item
    }
  }
}

for (const item of todos) {
  console.log(item)
}
Copy the code
  • B. Implement the iterator method
  1. ES Modules
  2. ES2016
  • A. Add an includes method
  • B. Exponential operators
  1. ES2017
  • A. Object extension method
  • B. You can add commas at the end of function parameters
  • c. Async/Await