I. JavaScript consists of three parts#
1. ECMAScript (Core)#
It defines the components of the language: syntax, types, statements, keywords, operators, etc.
2. DOM (Document Object Model)#
The DOM maps the entire page as a multi-layer node structure, allowing developers to easily delete, add, replace, or modify any node using the APIs provided by the DOM.
3. BOM (Browser Object Model)#
The browser object model supports access to and manipulation of the browser window, allowing developers to control parts of the browser that are outside the displayed page.
II. What is ES5?#
As the fifth version of ECMAScript (the fourth version was abandoned due to its complexity), the browser support situation can be seen in the first image, with the following added features.
1. Strict Mode#
Strict mode restricts certain usages, 'use strict';
2. Array Methods Added#
Added methods include every, some, forEach, filter, indexOf, lastIndexOf, isArray, map, reduce, reduceRight.
PS: There are other methods like Function.prototype.bind, String.prototype.trim, Date.now.
3. Object Methods#
- Object.getPrototypeOf
- Object.create
- Object.getOwnPropertyNames
- Object.defineProperty
- Object.getOwnPropertyDescriptor
- Object.defineProperties
- Object.keys
- Object.preventExtensions / Object.isExtensible
- Object.seal / Object.isSealed
- Object.freeze / Object.isFrozen
PS: Only discussing what exists, not what it is.
2. What is ES6?#
ECMAScript 6 provides a large number of new features while ensuring backward compatibility. The current browser compatibility situation is as follows:
ES6 features include:
-
Block scope keywords let, constant const
-
Object literal property value shorthand
var obj = {
// __proto__
__proto__: theProtoObj,
// Shorthand for ‘handler: handler’
handler,
// Method definitions
toString() {
// Super calls
return "d " + super.toString();
},
// Computed (dynamic) property names
[ 'prop_' + (() => 42)() ]: 42
};
- Destructuring assignment
let singer = { first: "Bob", last: "Dylan" };
let { first: f, last: l } = singer; // equivalent to f = "Bob", l = "Dylan"
let [all, year, month, day] = /^(\d\d\d\d)-(\d\d)-(\d\d)$/.exec("2015-10-25");
let [x, y] = [1, 2, 3]; // x = 1, y = 2
- Function parameters - default values, rest parameters, spread syntax (Default, Rest, Spread)
//Default
function findArtist(name='lu', age='26') {
...
}
//Rest
function f(x, ...y) {
// y is an Array
return x * y.length;
}
f(3, "hello", true) == 6
//Spread
function f(x, y, z) {
return x + y + z;
}
// Pass each elem of array as argument
f(...[1,2,3]) == 6
- Arrow functions
(1) Simplifies code syntax, automatically returns the result of the expression.
(2) Automatically binds the lexical this, i.e., the this of the function's definition. For example, the this used in the anonymous function parameter of forEach.
- Template strings
var name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`
// returns "Hello Bob, how are you today?"
- Iterators + for..of
Iterators have a next method that returns:
(1) An element of the iterable object: { done: false, value: elem }
(2) If it has reached the end of the iterable object: { done: true, value: retVal }
for (var n of ['a','b','c']) {
console.log(n);
}
// prints a, b, c
-
Generators
-
Class
Classes have constructor, extends, super, but essentially are syntactic sugar (they do not affect the functionality of the language but make it easier for programmers to use).
class Artist {
constructor(name) {
this.name = name;
}
perform() {
return this.name + " performs ";
}
}
class Singer extends Artist {
constructor(name, song) {
super.constructor(name);
this.song = song;
}
perform() {
return super.perform() + "[" + this.song + "]";
}
}
let james = new Singer("Etta James", "At last");
james instanceof Artist; // true
james instanceof Singer; // true
james.perform(); // "Etta James performs [At last]"
- Modules
The built-in module functionality of ES6 draws on the strengths of both CommonJS and AMD:
(1) It features the concise syntax of CommonJS, single exports, and cyclic dependencies.
(2) Similar to AMD, it supports asynchronous loading and configurable module loading.
// lib/math.js
export function sum(x, y) {
return x + y;
}
export var pi = 3.141593;
// app.js
import * as math from "lib/math";
alert("2π = " + math.sum(math.pi, math.pi));
// otherApp.js
import {sum, pi} from "lib/math";
alert("2π = " + sum(pi, pi));
Module Loaders:
// Dynamic loading – ‘System’ is default loader
System.import('lib/math').then(function(m) {
alert("2π = " + m.sum(m.pi, m.pi));
});
// Directly manipulate module cache
System.get('jquery');
System.set('jquery', Module({$: $})); // WARNING: not yet finalized
- Map + Set + WeakMap + WeakSet
Four types of collections, where WeakMap and WeakSet will be garbage collected if there are no other references to them.
// Sets
var s = new Set();
s.add("hello").add("goodbye").add("hello");
s.size === 2;
s.has("hello") === true;
// Maps
var m = new Map();
m.set("hello", 42);
m.set(s, 34);
m.get(s) == 34;
//WeakMap
var wm = new WeakMap();
wm.set(s, { extra: 42 });
wm.size === undefined
// Weak Sets
var ws = new WeakSet();
ws.add({ data: 42 });//Because the added object has no other references, it will not be held in the set
- Math + Number + String + Array + Object APIs
Some new APIs
Number.EPSILON
Number.isInteger(Infinity) // false
Number.isNaN("NaN") // false
Math.acosh(3) // 1.762747174039086
Math.hypot(3, 4) // 5
Math.imul(Math.pow(2, 32) - 1, Math.pow(2, 32) - 2) // 2
"abcde".includes("cd") // true
"abc".repeat(3) // "abcabcabc"
Array.from(document.querySelectorAll('*')) // Returns a real Array
Array.of(1, 2, 3) // Similar to new Array(...), but without special one-arg behavior
[0, 0, 0].fill(7, 1) // [0,7,7]
[1, 2, 3].find(x => x == 3) // 3
[1, 2, 3].findIndex(x => x == 2) // 1
[1, 2, 3, 4, 5].copyWithin(3, 0) // [1, 2, 3, 1, 2]
["a", "b", "c"].entries() // iterator [0, "a"], [1,"b"], [2,"c"]
["a", "b", "c"].keys() // iterator 0, 1, 2
["a", "b", "c"].values() // iterator "a", "b", "c"
Object.assign(Point, { origin: new Point(0,0) })
- Proxies
Using proxies to listen to operations on objects, allowing for corresponding actions to be taken.
var target = {};
var handler = {
get: function (receiver, name) {
return `Hello, ${name}!`;
}
};
var p = new Proxy(target, handler);
p.world === 'Hello, world!';
Operations that can be listened to: get, set, has, deleteProperty, apply, construct, getOwnPropertyDescriptor, defineProperty, getPrototypeOf, setPrototypeOf, enumerate, ownKeys, preventExtensions, isExtensible.
- Symbols
Symbol is a primitive type. Symbols are created by calling the symbol function, which takes an optional name parameter, and the symbol returned is unique.
var key = Symbol("key");
var key2 = Symbol("key");
key == key2 //false
- Promises
Promises are objects that handle asynchronous operations, allowing for a more intuitive organization of code using a chainable approach (similar to jQuery's deferred objects).
function fakeAjax(url) {
return new Promise(function (resolve, reject) {
// setTimeouts are for effect, typically we would handle XHR
if (!url) {
return setTimeout(reject, 1000);
}
return setTimeout(resolve, 1000);
});
}
// no url, promise rejected
fakeAjax().then(function () {
console.log('success');
},function () {
console.log('fail');
});