What are es6 and es5
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. .
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics





async is es7. async and await are new additions to ES7 and are solutions for asynchronous operations; async/await can be said to be syntactic sugar for co modules and generator functions, solving js asynchronous code with clearer semantics. As the name suggests, async means "asynchronous". Async is used to declare that a function is asynchronous; there is a strict rule between async and await. Both cannot be separated from each other, and await can only be written in async functions.

In ES6, you can use the reverse() method of the array object to achieve array reversal. This method is used to reverse the order of the elements in the array, putting the last element first and the first element last. The syntax "array.reverse()". The reverse() method will modify the original array. If you do not want to modify it, you need to use it with the expansion operator "...", and the syntax is "[...array].reverse()".

For browser compatibility. As a new specification for JS, ES6 adds a lot of new syntax and API. However, modern browsers do not have high support for the new features of ES6, so ES6 code needs to be converted to ES5 code. In the WeChat web developer tools, babel is used by default to convert the developer's ES6 syntax code into ES5 code that is well supported by all three terminals, helping developers solve development problems caused by different environments; only in the project Just configure and check the "ES6 to ES5" option.

Steps: 1. Convert the two arrays to set types respectively, with the syntax "newA=new Set(a);newB=new Set(b);"; 2. Use has() and filter() to find the difference set, with the syntax " new Set([...newA].filter(x =>!newB.has(x)))", the difference set elements will be included in a set collection and returned; 3. Use Array.from to convert the set into an array Type, syntax "Array.from(collection)".

In es5, you can use the for statement and indexOf() function to achieve array deduplication. The syntax "for(i=0;i<array length;i++){a=newArr.indexOf(arr[i]);if(a== -1){...}}". In es6, you can use the spread operator, Array.from() and Set to remove duplication; you need to first convert the array into a Set object to remove duplication, and then use the spread operator or the Array.from() function to convert the Set object back to an array. Just group.

In es6, the temporary dead zone is a syntax error, which refers to the let and const commands that make the block form a closed scope. Within a code block, before a variable is declared using the let/const command, the variable is unavailable and belongs to the variable's "dead zone" before the variable is declared; this is syntactically called a "temporary dead zone". ES6 stipulates that variable promotion does not occur in temporary dead zones and let and const statements, mainly to reduce runtime errors and prevent the variable from being used before it is declared, resulting in unexpected behavior.

No, require is the modular syntax of the CommonJS specification; and the modular syntax of the es6 specification is import. require is loaded at runtime, and import is loaded at compile time; require can be written anywhere in the code, import can only be written at the top of the file and cannot be used in conditional statements or function scopes; module attributes are introduced only when require is run. Therefore, the performance is relatively low. The properties of the module introduced during import compilation have slightly higher performance.

The map is ordered. The map type in ES6 is an ordered list that stores many key-value pairs. The key names and corresponding values support all data types; the equivalence of key names is determined by calling the "Objext.is()" method. Implemented, so the number 5 and the string "5" will be judged as two types, and can appear in the program as two independent keys.
