zishu's blog

zishu's blog

一个热爱生活的博主。https://zishu.me

What are the differences between ES5 and ES6?

I. JavaScript consists of three parts#

1. ECMAScript (Core)#

It specifies the components of the language: syntax, types, statements, keywords, operators, etc.

image

2. DOM (Document Object Model)#

The DOM maps the entire page as a multi-layered node structure, allowing developers to easily delete, add, replace, or modify any node using the APIs provided by the DOM.

image

3. BOM (Browser Object Model)#

The Browser Object Model supports accessing and manipulating parts of the browser window outside of the page displayed by the browser.

II. What is ES5?#

As the fifth version of ECMAScript (the fourth version was discarded 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:

  1. Block scope keywords let, constant const.

  2. 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
};
  1. 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
  1. 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
  1. Arrow functions.

(1) Simplifies code syntax, automatically returns the result of the expression.

(2) Automatically binds the lexical this, which is the this of the function's definition. For example, in the anonymous function parameter of forEach.

  1. Template strings.
var name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`
// returns "Hello Bob, how are you today?"
  1. Iterators + for..of.

Iterators have a next method that returns:

(1) An element of the iterable object: { done: false, value: elem }

(2) If at the end of the iterable object: { done: true, value: retVal }

for (var n of ['a','b','c']) {
  console.log(n);
}
// Prints a, b, c
  1. Generators.

  2. 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]"
  1. Modules.

The built-in module functionality of ES6 draws on the strengths of both CommonJS and AMD:

(1) Features a concise syntax of CommonJS, single exports, and cyclic dependencies.

(2) Similar to AMD, 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
  1. Map + Set + WeakMap + WeakSet.

Four types of collections, where WeakMap and WeakSet will be garbage collected if there are no other references to the objects as property keys.

// 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
  1. 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) })
  1. Proxies.

Using proxies to listen to operations on objects and then perform corresponding actions.

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.

  1. Symbols.

Symbol is a primitive type. A Symbol is 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
  1. Promises.

Promises are objects for handling 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');
});
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.