ES6 Syntax and Feature Overview(待续)

View on GitHub

Note: A commonly accepted practice is to use const except in cases of loops and reassignment. However, in this resource I‘ll be using let in place of var for all ES6 examples.

  • Variable: x
  • Object: obj
  • Array: arr
  • Function: func
  • Parameter, method: a, b, c
  • String: str

Table of contents

  • Variable declaration
  • Constant declaration
  • Arrow function syntax
  • Template literals
  • Implicit returns
  • Key/property shorthand
  • Method definition shorthand
  • Destructuring (object matching)
  • Array iteration (looping)
  • Default parameters
  • Spread syntax
  • Classes/constructor functions
  • Inheritance
  • Modules - export/import
  • Promises/callbacks

Variables and constant feature comparison

Understanding Variables, Scope, and Hoisting in JavaScript

Keyword Scope Hoisting Can Be Reassigned Can Be Redeclared
var Function scope Yes Yes Yes
let Block scope No Yes No
const Block scope No No No

Variable declaration

ES6 introduced the let keyword, which allows for block-scoped variables which cannot be hoisted or redeclared.

MDN Reference: let

Constant declaration

ES6 introduced the const keyword, which cannot be redeclared or reassigned, but is not immutable.

MDN Reference: const

Arrow functions

The arrow function expression syntax is a shorter way of creating a function expression. Arrow functions do not have their own this, do not have prototypes, cannot be used for constructors, and should not be used as object methods.

# ES5

function func(a, b, c) {} // function declaration
var func = function(a, b, c) {} // function expression

#ES6

let func = a => {} // parentheses optional with one parameter
let func = (a, b, c) => {} // parentheses required with multiple parameters

  MDN Reference: Arrow functions

Template literals(模板文字)

Concatenation/string interpolation

Expressions can be embedded in template literal strings.

# ES5

var str = ‘Release date: ‘ + date

# ES6

let str = `Release Date: ${date}`

  MDN Reference: Expression interpolation

Multi-line strings

Using template literal syntax, a JavaScript string can span multiple lines without the need for concatenation.

#ES5

var str = ‘This text ‘ + ‘is on ‘ + ‘multiple lines‘

# ES6

let str = `This text
            is on
            multiple lines`

  

Note: Whitespace is preserved in multi-line template literals. See Removing leading whitespace in ES6 template strings.

Implicit returns

The return keyword is implied and can be omitted if using arrow functions without a block body.

# ES5

function func(a, b, c) {
  return a + b + c
}

# ES6

let func = (a, b, c) => a + b + c // curly brackets must be omitted

 MDN Reference: Function body

Key/property shorthand

ES6 introduces a shorter notation for assigning properties to variables of the same name.

# ES5

var obj = {
  a: a,
  b: b,
}

# ES6

let obj = {
  a,
  b,
}

  MDN Reference: Property definitions

Method definition shorthand

The function keyword can be omitted when assigning methods on an object.

# ES5

var obj = {
  a: function(c, d) {},
  b: function(e, f) {},
}

# ES6

let obj = {
  a(c, d) {},
  b(e, f) {},
}
obj.a() // call method a

  MDN Reference: Method definitions

Destructuring (object matching)

Use curly brackets to assign properties of an object to their own variable.

var obj = { a: 1, b: 2, c: 3 }

# ES5

var a = obj.a
var b = obj.b
var c = obj.c

# ES6

let { a, b, c } = obj

  MDN Reference: Object initializer

Array iteration (looping)

A more concise syntax has been introduced for iteration through arrays and other iterable objects.

var arr = [‘a‘, ‘b‘, ‘c‘]

# ES5

for (var i = 0; i < arr.length; i++) {
  console.log(arr[i])
}

# ES6

for (let i of arr) {
  console.log(i)
}

  MDN Reference: for...of

Default parameters

Functions can be initialized with default parameters, which will be used only if an argument is not invoked through the function.

# ES5

var func = function(a, b) {
  b = b === undefined ? 2 : b
  return a + b
}

# ES6

let func = (a, b = 2) => {
  return a + b
}

func(10) // returns 12
func(10, 5) // returns 15

  MDN Reference: Default paramters

Spread syntax

Spread syntax can be used to expand an array.

# ES6

let arr1 = [1, 2, 3]
let arr2 = [‘a‘, ‘b‘, ‘c‘]
let arr3 = [...arr1, ...arr2]

console.log(arr3) // [1, 2, 3, "a", "b", "c"]

Spread syntax can be used for function arguments.

# ES6

let arr1 = [1, 2, 3]
let func = (a, b, c) => a + b + c

console.log(func(...arr1)) // 6

  MDN Reference: Spread syntax

Classes/constructor functions

ES6 introducess the class syntax on top of the prototype-based constructor function.

# ES5

function Func(a, b) {
  this.a = a
  this.b = b
}

Func.prototype.getSum = function() {
  return this.a + this.b
}

var x = new Func(3, 4)

# ES6

class Func {
  constructor(a, b) {
    this.a = a
    this.b = b
  }

  getSum() {
    return this.a + this.b
  }
}

let x = new Func(3, 4)

x.getSum() // returns 7

  MDN Reference: Classes

Inheritance

The extends keyword creates a subclass.

# ES5

function Inheritance(a, b, c) {
  Func.call(this, a, b)

  this.c = c
}

Inheritance.prototype = Object.create(Func.prototype)
Inheritance.prototype.getProduct = function() {
  return this.a * this.b * this.c
}

var y = new Inheritance(3, 4, 5)

# ES6

class Inheritance extends Func {
  constructor(a, b, c) {
    super(a, b)

    this.c = c
  }

  getProduct() {
    return this.a * this.b * this.c
  }
}

let y = new Inheritance(3, 4, 5)

y.getProduct() // 60

  MDN Reference: Subclassing with extends

Modules - export/import

Modules can be created to export and import code between files.

# index.html

<script src="export.js"></script>
<script type="module" src="import.js"></script>

# export.js

let func = a => a + a
let obj = {}
let x = 0

export { func, obj, x }

# import.js

import { func, obj, x } from ‘./export.js‘

console.log(func(3), obj, x)

  

Promises/Callbacks

Promises represent the completion of an asynchronous function. They can be used as an alternative to chaining functions.

# ES5 callback

function doSecond() {
  console.log(‘Do second.‘)
}

function doFirst(callback) {
  setTimeout(function() {
    console.log(‘Do first.‘)

    callback()
  }, 500)
}

doFirst(doSecond)

# ES6 Promise

let doSecond = () => {
  console.log(‘Do second.‘)
}

let doFirst = new Promise((resolve, reject) => {
  setTimeout(() => {
    console.log(‘Do first.‘)

    resolve()
  }, 500)
})

doFirst.then(doSecond)

  

An example below using XMLHttpRequest, for demonstrative purposes only (Fetch API would be the proper modern API to use).

# ES5 callback

function makeRequest(method, url, callback) {
  var request = new XMLHttpRequest()

  request.open(method, url)
  request.onload = function() {
    callback(null, request.response)
  }
  request.onerror = function() {
    callback(request.response)
  }
  request.send()
}

makeRequest(‘GET‘, ‘https://url.json‘, function(err, data) {
  if (err) {
    throw new Error(err)
  } else {
    console.log(data)
  }
})

# ES6 Promise

function makeRequest(method, url) {
  return new Promise((resolve, reject) => {
    let request = new XMLHttpRequest()

    request.open(method, url)
    request.onload = resolve
    request.onerror = reject
    request.send()
  })
}

makeRequest(‘GET‘, ‘https://url.json‘)
  .then(event => {
    console.log(event.target.response)
  })
  .catch(err => {
    throw new Error(err)
  })

  

If you found this useful, please share!

 

原文地址:https://www.cnblogs.com/panpanwelcome/p/11758034.html

时间: 2024-10-13 06:45:26

ES6 Syntax and Feature Overview(待续)的相关文章

ES6语法糖集锦

sublime3安装Es6插件 javascriptNext,然后安装即可 Java?Script?Next - ES6 Syntax()高亮插件 ----------------------------------------------------------------- let.const命令 与var声明 let块级作用域 let不允许在代码块内重复声明一个变量 function aa(){ let a=3 { let a=5 //子作用域 } } 使用var声明的变量,其作用域为该语

Markdown: Syntax

Markdown: Syntax Main Basics Syntax License Dingus Overview Philosophy Inline HTML Automatic Escaping for Special Characters Block Elements Paragraphs and Line Breaks Headers Blockquotes Lists Code Blocks Horizontal Rules Span Elements Links Emphasis

dfsdf

This project was bootstrapped with Create React App. Below you will find some information on how to perform common tasks. You can find the most recent version of this guide here. Updating to New Releases Create React App is divided into two packages:

嵌入式web服务器

现在在嵌入式设备中所使用的web服务器主要有:boa.thttpd.mini_httpd.shttpd.lighttpd.goaheand.appweb和apache等. Boa 1.介绍 Boa诞生于1991年,作者Paul Philips.是开源的,应用很广泛,特别适合于嵌入式设备,网上流行程度很广.它的官方网站说boa是最受人喜爱的嵌入式web服务器.功能较为强大,支持认证,cgi等.Boa 是一个单任务的HTTP SERVER,它不像传统的web服务器那样为每个访问连接开启一个进程,也不

嵌入式web服务

:boa.thttpd.mini_httpd.shttpd.lighttpd.goaheand.appweb和apache等. Boa 1.介绍 Boa诞生于1991年,作者Paul Philips.是开源的,应用很广泛,特别适合于嵌入式设备,网上流行程度很广.它的官方网站说boa是最受人喜爱的嵌入式web服务器.功能较为强大,支持认证,cgi等.Boa 是一个单任务的HTTP SERVER,它不像传统的web服务器那样为每个访问连接开启一个进程,也不会为多个连接开启多个自身的拷贝.Boa对所有

All About Angular 2.0

angular All About Angular 2.0 Posted by Rob Eisenberg on  November 6th, 2014. Have questions about the strategy for Angular 2.0? This is the place. In the following article I'll explain the major feature areas of Angular 2.0 along with the motivation

Spring框架文档与API(4.3.6版本)

http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/ Table of Contents I. Overview of Spring Framework 1. Getting Started with Spring 2. Introduction to the Spring Framework 2.1. Dependency Injection and Inversion of Contr

【转】3 Essential Sublime Text Plugins for Node &amp; JavaScript Developers

原文转自:http://scottksmith.com/blog/2014/09/29/3-essential-sublime-text-plugins-for-node-and-javascript-developers/ Check out these 3 great and essential Sublime Text plugins every JavaScript and Node developer should know about and use. JsFormat https:

Installation and Upgrading

Cumulative Feature Overview Identifies product features available to you when upgrading. This tool requires Microsoft Excel. Any user should consult this document, as needed. Note: Make sure to enable macros when prompted to do so. Otherwise, the Mic