- function fn() {
- let x = 0
- if (true) {
- let x = 1 // only inside this `if`
- }
- }
- const a = 1
is the new
- let
. Constants work just like
- var
, but can’t be reassigned. See: Let and const
- let
- var message = `Hello ${name}`
- var str = `
- hello
- world
- `
Templates and multiline strings. See: Template strings
- let bin = 0b1010010
- let oct = 0o755
See: Binary and octal literals
- "hello".repeat(3)
- "hello".includes("ll")
- "\u1E9B\u0323".normalize("NFC")
See: New methods
- class Circle extends Shape {
- constructor(radius) {
- this.radius = radius
- }
- getArea() {
- return Math.PI * 2 * this.radius
- }
- expand(n) {
- return super.expand(n) * Math.PI
- }
- static createFromDiameter(diameter) {
- return new Circle(diameter / 2)
- }
- }
Syntactic sugar for prototypes. See: Classes
- const byte = 2 ** 8
- // Same as: Math.pow(2, 8)
- new Promise((resolve, reject) => {
- if (ok) { resolve(result) }
- else { reject(error) }
- })
For asynchronous programming. See: Promises
- promise
- .then((result) => { ··· })
- .catch((error) => { ··· })
- Promise.all(···)
- Promise.race(···)
- Promise.reject(···)
- Promise.resolve(···)
- async function run () {
- const user = await getUser()
- const tweets = await getTweets(user)
- return [user, tweets]
- }
functions are another way of using functions.
- async
See: async function
- var [first, last] = ['Nikola', 'Tesla']
- let {title, author} = {
- title: 'The Silkworm',
- author: 'R. Galbraith'
- }
Supports for matching arrays and objects. See: Destructuring
- var scores = [22, 33]
- var [math = 50, sci = 50, arts = 50] = scores
- // Result:
- // math === 22, sci === 33, arts === 50
Default values can be assigned while destructuring arrays or objects.
- function greet({ name, greeting }) {
- console.log(`${greeting}, ${name}!`)
- }
- greet({ name: 'Larry', greeting: 'Ahoy' })
Destructuring of objects and arrays can be also be done in function arguments.
- function printCoordinates({ left: x, top: y }) {
- console.log(`x: ${x}, y: ${y}`)
- }
- printCoordinates({ left: 25, top: 90 })
This example assigns
to the value of the
- x
key.
- left
- for (let {title, artist} in songs) {
- ···
- }
The assignment expressions work in loops, too.
- const options = {
- ...defaults,
- visible: true
- }
- const options = Object.assign(
- {}, defaults,
- { visible: true })
The Object spread operator lets you build new objects from other objects.
See: Object spread
- const users = [
- ...admins,
- ...editors,
- 'rstacruz'
- ]
- const users = admins
- .concat(editors)
- .concat([ 'rstacruz' ])
The spread operator lets you build new arrays in the same way.
See: Spread operator
- function greet (name = 'Jerry') {
- return `Hello ${name}`
- }
- function fn(x, ...y) {
- // y is an Array
- return x * y.length
- }
- fn(...[1, 2, 3])
- // same as fn(1, 2, 3)
Default, rest, spread. See: Function arguments
- setTimeout(() => {
- ···
- })
- readFile('text.txt', (err, data) => {
- ...
- })
- numbers.map(n => n * 2)
- // No curly braces = implicit return
- // Same as: numbers.map(function (n) { return n * 2 })
Like functions but with
preserved. See: Fat arrows
- this
- module.exports = { hello, bye }
- // Same as: module.exports = { hello: hello, bye: bye }
See: Object literal enhancements
- const App = {
- start () {
- console.log('running')
- }
- }
- // Same as: App = { start: function () {···} }
See: Object literal enhancements
- const App = {
- get closed() {
- return this.status === 'closed'
- },
- set closed(value) {
- this.status = value ? 'closed': 'open'
- }
- }
See: Object literal enhancements
- let event = 'click'
- let handlers = {
- [`on${event}`]: true
- }
- // Same as: handlers = { 'onclick': true }
See: Object literal enhancements
- import 'helpers'
- // aka: require('···')
- import Express from 'express'
- // aka: Express = require('···').default || require('···')
- import { indent } from 'helpers'
- // aka: indent = require('···').indent
- import * as Helpers from 'helpers'
- // aka: Helpers = require('···')
- import { indentSpaces as indent } from 'helpers'
- // aka: indent = require('···').indentSpaces
is the new
- import
. See: Module imports
- require()
- export default function () { ··· }
- // aka: module.exports.default = ···
- export function mymethod () { ··· }
- // aka: module.exports.mymethod = ···
- export const pi = 3.14159
- // aka: module.exports.pi = ···
is the new
- export
. See: Module exports
- module.exports
- function* idMaker () {
- var id = 0
- while (true) { yield id++ }
- }
- var gen = idMaker() gen.next().value // → 0
- gen.next().value // → 1
- gen.next().value // → 2
It’s complicated. See: Generators
- for (let i of iterable) {
- ···
- }
For iterating through generators and arrays. See: For..of iteration
来源: https://juejin.im/entry/5a026940f265da4321537754