banner
ming5ming

ming5ming

⭐一起去追那遥不可及的星⭐ 正在赛马!

Javascript

ES6 Basics#

Object Literal#
  1. Property Value Shorthand
var events = {
	listeners: listeners,
	listen: listen;
}

==>

var events = { listeners, listen }
  1. Computed Property Names

If there is a variable var expertise = 'journalism'
then you can add a property to an object like this:

var person = {
	name: 'gui',
	age: 27
}

person[expertise] = {
	years: 5,
	interests: ['a', 'b', 'c']
}
  1. Method Definitions

Declare methods for an object by adding properties

var emitter = {
	on: function (a, b) {
	...
	}
}

==>

var emitter = {
	on(a,b) {
	...
	}
}
Arrow Functions#
  1. Scope

Arrow functions do not create a new scope, they share the same scope as their parent. They do not create closures.

var timer = {
	seconds: 0,
	start() {
		setInterval(() => {
		this.seconds++
		},1000)
	}
}
//this refers to the scope of the timer block
timer.start()
  1. Syntax

Use parentheses when returning an object:

var objectFactory = () => ({ modular: 'es6' })
Destructuring#
  1. Object Destructuring

If there is an object like this:

var character = {
	name: 'Bruce',
	pseudonym: 'Batman',
	metadata: {
		age: 34,
		gender: 'male'
		}
}

You can access its properties like this:

var { pseudonym } = character

Or assign an alias to it:

var { pseudonym: pseudonymAlias } = character

Deep destructuring:

var { metadata: { gender } } = character

Deep destructuring with alias:

var { meatadata: { gender: characterGender } } = character
  1. Array Destructuring

Basic form:

var lst = ['a', 'b', 'c']
var [x, y, z] = lst;

Skipping elements:

var [x, , z] = lst;

Default values:

var [ x = 'x', , z = 'z'] = lst;

Swapping values:

var left = 5
var right = 8
[left, right] = [right, left]
  1. Default Function Parameters

Default values for arrow functions:

var double = (input = 0) => input * 2
  1. Destructuring Function Parameters

Basic form:

function foo({ brand = 'Volkswagen', make = 1999 }) {
	console.log(brand)
	console.log(make)
}
foo({ make: 2000 })
//<= 'Volkswagen'
//<= 2000
foo()
//<= Error

Default values:

function foo({ brand = 'Volkswagen', make = 1999 } = {} ) {
	console.log(brand)
	console.log(make)
	}
foo()
//<= 'Volkswagen'
//<= 2000
Rest Parameters and Spread Operator#
  1. Rest Parameters
  2. Spread Operator
    Convert iterable objects to arrays
[...'show me']
//<- ['s', 'h', 'o', 'w', ' ', 'm', 'e']
Template Literals#

Use backticks ` to represent template literals:

var text = `Hello "World"`
  1. String Interpolation
`Hello, ${ 2 + 3 }`
//<- "Hello, 6"
  1. Tagged Templates
//For tagged templates
tag`Hello, ${name}. I am ${ emotion } to meet you!`
//The function call is like this
tag(
	['Hello, ', '. I am ', ' to meet you!'],
	'Maurice',
	'thrilled'
)
//The implementation of the tag function is like this
function tag(parts, ...values) {
	return parts.reduce(
		(all, part, index) => all + values[index - 1] + part
	)
}

Classes, Symbols, Objects, and Decorators#

Classes#
Prototypes
function Fruit(name, calories) {
	this.name = name
	this.calories = calories
	this.pieces = 1
}

Fruit.prototype.chop = function () {
	this.pieces++
}
Fruit.prototype.bite = function (person) {
	...
}
Classes
class Fruit {
	constructor(name, calories) {
		this.name = name
		this.calories = calories
		this.pieces = 1**
	}
	chop() {
		this.pieces++
	}
	bite(person) {
		...
	}
}
Class Expression
const Person = class {
	constructor(name) {
		this.name = name 
	}
}
Class Factory Function
const createPersonClass = name => class extends Person {
	constructor() {
		super(name)
	}
}

const JackePerson = createPersonClass('Jake')
const jake = new JackePerson()

Storing and retrieving data with the same key in a class:

class LocalStorage {
	constructor(key) {
		this.key = key
	}
	get data() {
		return JSON.parse(localStorage.getItem(this.key))
	}
	set data(data) {
		localStorage.setItem(this.key, JSON.stringify(data))
	}
}
Static Methods
//Prototype Chain
function Person() {
	...
}
Person.isPerson = function (person) {
	return person instanceof Person
}
//Class
class Person() {
	...
	static isPerson() {
		...
	}
}
Class Inheritance
//Prototype Inheritance
function Banana() {
	Fruit.call(this, 'banana', 105)
}
Banana.prototype = Object.creat(Fruit.prototype)
Banana.prototype.slice = function() {
	...
}
//Class Inheritance -> Use the extends keyword
Object.assign

Merge objects

function md(input, options) {
	const config = Object.assgign({}, defaults, options)
}
//defaults is assigned to {}, then options is assigned to {}
//User-provided properties will override the defaults

Object.assign does not deep clone objects

Object.assign({}, { a: { b: 'c', d: 'e' } }, { a: { f: 'g' } })
// <- { a: { f: 'g' } }

Prefer using the spread operator for assignment:

const grocery = { ...details }
// Object.assign({}, details)
const grocery = { type: 'fruit', ...details }
// Object.assign({ type: 'fruit' }, details)
const grocery = { type: 'fruit', ...details, ...fruit }
// Object.assign({ type: 'fruit' }, details, fruit)
const grocery = { type: 'fruit', ...details, color: 'red' }
// Object.assign({ type: 'fruit' }, details, { color: 'red' })
Object.is
NaN === NaN
// <- false
Object.is(NaN, NaN)
// <- true
-0 === +0
// <- true
Object.is(-0, +0)
// <- false
Object.setPrototypeOf

Change the prototype of an existing object, has performance issues

//ES5
const baseCat = { type: 'cat', legs: 4 }
const cat = Object.create(baseCat)
cat.name = 'Milanesita'
//ES6
const baseCat = { type: 'cat', legs: 4 }
const cat = Object.setPrototypeOf(
{ name: 'Milanesita' },
baseCat
)
Symbols#
Local Symbols (create wrapper objects, store references, or reflect access)
  1. Creating Symbols
const first = Symbol('something')
//Uniqueness
console.log(Symbol() === Symbol())
// <- false
console.log(Symbol('my symbol') === Symbol('my symbol'))
// <- false
  1. Using Symbols as Property Names
const weapon = Symbol('weapon')
const character = {
	name: 'Penguin'
	[weapon]: 'umbrella'
}
  1. Symbols properties cannot be accessed using for...in, Object.keys, Object.getOwnPropertyNames
  2. Can be accessed using Object.getOwnPropertySymbols
console.log(Object.getOwnPropertySymbols(character))
// <- [Symbol(weapon)]
Using Symbols

...

Decorators#

Class decorator functions take three arguments: the constructor of the class being decorated, the heritage if the decorated class inherits from another class, and an array of member descriptors with the decorated class's members.

Iteration and Flow Control#

To be write

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.