Home  >  Article  >  Web Front-end  >  What are es6 and es5

What are es6 and es5

奋力向前
奋力向前Original
2021-09-10 12:14:415305browse

ECMAScript is a script programming language standardized by Ecma International through ECMA-262. The full name of es6 is ECMAScript 6, which is the sixth version of ECMAScript; the full name of es5 is ECMAScript 5, which is the fifth version of ECMAScript. .

What are es6 and es5

The operating environment of this tutorial: Windows 7 system, Dell G3 computer.

ECMAScript is a scripting programming language standardized by Ecma International through ECMA-262. This language is widely used on the World Wide Web. It is often called JavaScript or JScript, so it can be understood as a standard for JavaScript, but in fact the latter two are implementations and extensions of the ECMA-262 standard.

What is ES5

As the fifth version of ECMAScript (the fourth version was abandoned because it was too complex), browser support can be seen in the first picture. The added features are as follows.

1. strict mode

Strict mode, restrict some usage, 'use strict';

2. Add Array method

Added every, some, forEach, filter, indexOf, lastIndexOf, isArray, map, reduce, reduceRight methods PS: There are other methods Function.prototype.bind, String.prototype.trim, Date.now

3. Object method

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 talk about what is there, not what it is.

What is ES6

ECMAScript6 provides a large number of new features while ensuring downward compatibility. The current browser compatibility is as follows: ES6 features are as follows:

1. Block-level scope keyword let, constant const

2. Property value shorthand for object literals

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
};

3. Assignment and destructuring

let singer = { first: "Bob", last: "Dylan" };
let { first: f, last: l } = singer; // 相当于 f = "Bob", l = "Dylan"
let [all, year, month, day] =  /^(dddd)-(dd)-(dd)$/.exec("2015-10-25");
let [x, y] = [1, 2, 3]; // x = 1, y = 2

4. Function parameters - default value, parameter packaging, array expansion (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

5. Arrow functions

(1). The code form is simplified and the expression result is returned by default.

(2). Automatically bind semantic this, that is, this when defining a function. As in the above example, this is used in the anonymous function parameter of forEach.

6. String template Template strings

var name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`
// return "Hello Bob, how are you today?"

7. Iterators for..ofThe iterator has a next method, The call will return:

(1). Return an element of the iteration object: { done: false, value: elem }

(2). If the end of the iteration object has been reached: { done : true, value: retVal }

for (var n of ['a','b','c']) {
  console.log(n);
}
// 打印a、b、c

8.Generators

9.Class

Class, There are constructor, extends, and super, but they are essentially syntactic sugar (have no impact on the functionality of the language, but are more convenient 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]"

10.Modules

The built-in module function of ES6 draws on the respective advantages of CommonJS and AMD: (1). It has the streamlined syntax and unique export of CommonJS ( single exports) and cyclic dependencies (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

11.Map Set WeakMap WeakSet Four collection types, WeakMap and WeakSet objects as property keys will be recycled and released if no other variables refer 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

12.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) })

13. ProxiesUse a proxy (Proxy) to monitor the operation of the object , and then you can do some corresponding things.

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 monitored: get, set, has, deleteProperty, apply, construct, getOwnPropertyDescriptor, defineProperty, getPrototypeOf, setPrototypeOf, enumerate, ownKeys, preventExtensions, isExtensible.

14.Symbols Symbol is a basic type. Symbol is generated by calling the symbol function, which receives an optional name parameter. The symbol returned by this function is unique.

var key = Symbol("key");
var key2 = Symbol("key");
key == key2  //false

15.Promises

Promises are objects that handle asynchronous operations. After using the Promise object, you can use a chain call method to organize the code so that the code More intuitive (similar to jQuery's deferred object).

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');
});

Summary

For ES6, will it repeat the mistakes of ES4 in some ways and become more complicated? Or maybe everyone’s acceptance will become stronger after a few years, and I think it should be That’s it. I think it's good because they are backward compatible. Even if you don't know the complex syntax, you can still use the methods you are familiar with, and the syntax sugar they provide is quite practical. This article is a bit long, so I’ll end it here. This article aims to talk about what is there, and it should cover most of the content, but there is no detailed analysis. Some of the content comes from online materials, so I will not list them one by one.

Recommended learning: JS video tutorial

The above is the detailed content of What are es6 and es5. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Is vuejs the same as php?Next article:Is vuejs the same as php?