JavaScript study notes (xiii) ES6 new features

In this article we will introduce ES2015 / ES6 some of the new features in common

1, variable definitions

Before ES6, define variables can only use varkeywords, and add in the ES6 letand constkeywords, the difference between them is as follows:

Keyword Scope Whether a variable lift You can duplicate definitions
var Function scope Yes can
letconst Block-level scope no no
function function_scope() {
    console.log(result) // undefined
    var result = 0
    for (var count = 1; count <= 5; count++) { result += count }
    console.log(count) // 5
    return result
}

function block_scope() {
    // console.log(result) -> ReferenceError: result is not defined
    let result = 0
    for (let count = 1; count <= 5; count++) { result += count }
    // console.log(count) -> ReferenceError: count is not defined
    return result
}

letAnd constthe difference between the following:

  • Use constdefined variables must be assigned at the time of the statement, but letdo not
  • Use constcan not be modified after the definition of variable declarations, but letwill not
// const a -> Uncaught SyntaxError: Missing initializer in const declaration
const a = 0
// a = 1 -> Uncaught TypeError: Assignment to constant variable.

Note Oh, mentioned here can not be changed, not to say that the values ​​of variables can not be modified, but the identifier variables can not be reassigned

Precisely, the variables declared const is a read-only reference value, it means that the address space of the stack can not be changed, rather than the value of the heap space can not be modified

So for reference types, we can modify its value

const a = [1, 3, 5]
a[0] = 2
console.log(a) // (3) [2, 3, 5]

2, the array iteration

Before ES6, there are two ways to use a for loop iteration arrays, which are traditional for loop and for...inloop

let array = ['a', 'b', 'c']
// 传统 for 循环
for (let index = 0; index < array.length; index++) {
    console.log(index + ': ' + array[index])
}
// for...in 循环
for (let index in array) {
    console.log(index + ': ' + array[index])
}

/*
 * 执行结果:
 * 0: a
 * 1: b
 * 2: c
**/

The new ES6 in the for...ofloop, you can iterate the array elements directly, rather than the array index

let array = ['a', 'b', 'c']
// for...of 循环
for (let item of array) {
    console.log(item)
}

/*
 * 执行结果:
 * a
 * b
 * c
**/

In for...ofcan also use the loop continueand breakstatements

let array = [1, 2, 3, 4, 5, 6, 7, 8]
let sum = 0
for (let item of array) {
    if (item % 2 === 0) continue
    sum += item
}
console.log(sum) // 16

3, template string

Template string is very convenient in a multi-line strings and string concatenation and other scenes

  • Before ES6
// 多行字符串
let html = '<ul>' + 
    '<li>Apple</li>' +
    '<li>Banana</li>' +
    '<li>Cherry</li>' +
    '</ul>'
console.log(html)
// 字符串拼接
let protocol = 'https'
let host = '127.0.0.1'
let port = '80'
let path = 'index.html'
let url = protocol + '://' + host + ':' + port + '/' + path
console.log(url) /* http://127.0.0.1:80/index.html */
  • After ES6
// 多行字符串,保留原有格式
let html = `
<ul>
    <li>Apple</li>
    <li>Banana</li>
    <li>Cherry</li>
</ul>
`
console.log(html)
// 字符串拼接,可以使用变量
let protocol = 'https'
let host = '127.0.0.1'
let port = '80'
let path = 'index.html'
let url = `${protocol}://${host}:${port}/${path}`
console.log(url) /* http://127.0.0.1:80/index.html */

4, deconstruction grammar

Deconstruction value syntax arrays and objects can be extracted and assigned to a new variable

  • Before ES6
// 数组解构
let array = ['a', 'b', 'c']
let x = array[0]
let y = array[1]
let z = array[2]
console.log(x, y ,z) // a b c
// 对象解构
let object = { name: 'Steve', age: 18 }
let name = object.name
let age = object.age
console.log(name, age) // Steve 18
  • After ES6
// 数组解构
let array = ['a', 'b', 'c']
let [x, y, z] = array
console.log(x, y, z) // a b c
// 对象解构,变量名要与属性名相同
let object = { name: 'Steve', age: 18 }
let {name, age} = object
console.log(name, age) // Steve 18

5, extended operator

Expanding operator array can be converted to a parameter sequence separated by commas

  • Before ES6
// 数组复制
let array = ['a', 'b', 'c']
let array_copy = array.concat()
console.log(array_copy) // (3) ["a", "b", "c"]
// 数组合并
let array_one = ['a', 'b', 'c']
let array_two = ['d', 'e', 'f']
let array_merge = array_one.concat(array_two)
console.log(array_merge) // (6) ["a", "b", "c", "d", "e", "f"]
// 接收函数参数,所有传入的参数都会保存在 arguments 中
function add() {
    let result = 0
    Array.prototype.forEach.call(arguments, function(item) { result += item })
    return result
}
let result = add(1, 2, 3)
console.log(result) // 6
  • After ES6
// 数组复制
let array = ['a', 'b', 'c']
let array_copy = [...array]
console.log(array_copy) // (3) ["a", "b", "c"]
// 合并数组
let array_one = ['a', 'b', 'c']
let array_two = ['d', 'e', 'f']
let array_merge = [...array_one, ...array_two]
console.log(array_merge) // (6) ["a", "b", "c", "d", "e", "f"]
// 接收函数参数,剩余参数作为函数的最后一个参数,将传入的参数以数组的形式储存起来
function add(...array) {
    let result = 0
    array.forEach(function(item) { result += item })
    return result
}
let result = add(1, 2, 3)
console.log(result) // 6

6, the default parameters

When the function definition, the default value may be provided directly to the function parameters

  • Before ES6
function greet(somebody) {
    var somebody = somebody || 'stranger'
    console.log('Hello, ' + somebody)
}
greet('Amy') // Hello, Amy
greet() // Hello, stranger
  • After ES6
function greet(somebody = 'stranger') {
    console.log('Hello, ' + somebody)
}
greet('Amy') // Hello, Amy
greet() // Hello, stranger

7, arrow function

Use the arrows to function not only can more easily defined functions, and this value will inherit the value of this execution context of the parent

  • Before ES6
// 过滤奇数,元素累加
let sum = 0
let arr = [1, 2, 3, 4, 5]
let even = arr.filter(function(item) { return item % 2 === 0 })
even.forEach(function(item) { sum = sum + item })
console.log(sum) // 6
// this 取值
let object = {
    value: 'hello',
    print: function() {
        // 使用 bind 函数将 this 的值绑定好
        setTimeout(function() { console.log(this.value) }.bind(this), 1000)
    }
}
object.print() // hello
  • After ES6
// 过滤奇数,元素累加
let sum = 0
let arr = [1, 2, 3, 4, 5]
let even = arr.filter((item) => (item % 2 === 0))
even.forEach((item) => { sum = sum + item })
console.log(sum) // 6
// this 取值
let object = {
    value: 'hello',
    print: function() {
        // 使用箭头函数,this 的值将会继承父级执行上下文(在这里是 print 函数)this 的值
        setTimeout(() => { console.log(this.value) }, 1000)
    }
}
object.print() // hello

8, class

class Keyword is used to define the class, it is not a new mode of inheritance, but nothing prototype chain of syntactic sugar

  • Before ES6
// 定义类
function Person(name, age) {
    this.name = name
    this.age = age
}
// 公有实例方法
Person.prototype.sayHello = function() {
    console.log('Hello, I am ' + this.name)
}
// 类继承
function Worker(name, age, salary) {
  Person.call(this, name, age)
  this.salary = salary || 100
}
// 公有实例方法
Worker.prototype.sayHello = function() {
    Person.prototype.sayHello.call(this)
    console.log('My salary is $' + this.salary)
}
// 公有实例方法
Worker.prototype.changeSalary = function(value) {
    this.salary += value
}

let person = new Person('Steve', 18)
person.sayHello() // Hello, I am Steve
let worker = new Worker('Steven', 20, 100)
worker.sayHello() // Hello, I am Steven // My salary is $100
worker.changeSalary(100)
worker.sayHello() // Hello, I am Steven // My salary is $200
  • After ES6
// 定义类
class Person {
    // 构造函数
    constructor(name, age) {
        this.name = name
        this.age = age
    }
    // 公有实例方法
    sayHello() {
        console.log('Hello, I am ' + this.name)
    }
}
// 类继承
class Worker extends Person {
    // 构造函数
    constructor(name, age, salary = 100) {
        super(name, age) // 调用父类初始化函数
        this.salary = salary
    }
    // 公有实例方法
    sayHello() {
        super.sayHello() // 调用父类的实例方法
        console.log('My salary is $' + this.salary)
    }
    // 公有实例方法
    changeSalary(value) {
        this.salary += value
    }
}

let person = new Person('Steve', 18)
person.sayHello() // Hello, I am Steve
let worker = new Worker('Steven', 20, 100)
worker.sayHello() // Hello, I am Steven // My salary is $100
worker.changeSalary(100)
worker.sayHello() // Hello, I am Steven // My salary is $200

[Read More JavaScript series of articles, look at JavaScript study notes ]

Guess you like

Origin www.cnblogs.com/wsmrzx/p/12244036.html