In ES5, a class is defined by a constructor and a prototype. In ES6, we can define a class by a class.
How to define a class in ES5, you can see this article “class”, we here mainly talk about es5 class and ES6 class difference.
The class must be called new, not executed directly.
Class will report an error when executed, but es5 classes are not fundamentally different from normal functions.
There is no variable promotion for class
Figure 2 reports an error indicating that the class approach does not promote the class definition to the top.
Class cannot traverse properties and methods on its instance stereotype chain
function Foo (color) { this.color = color } Foo.prototype.like = function () { console.log(`like${this.color}`) } let Foo = new foo () for (let key in foo) {// the stereotype like is printed console.log(key) // color, like}Copy the code
class Foo { constructor (color) { this.color = color } like () { console.log(`like${this.color}`) } } let foo = new Foo('red') for (let key in Foo) {// print only a color, not print like console.log(key) // color}Copy the code
New. Target attribute
Es6 introduces a new.target attribute for the new command, which returns the constructor on which the new command operates. New.target returns undefined if not called via new or reflect.construct ()
function Person(name) { if (new.target === Person) { this.name = name; } else {throw new Error(' must use new command to generate an instance '); }} let Person = {} Person. Call (obj, 'red')Copy the code
Class has static methods
Static methods can only be called from the class, not from the instance; Also, if the static method contains the this keyword, this refers to the class, not the instance. Static properties and methods in a static declaration can be inherited by subclasses.
class Foo { static bar() { this.baz(); } static baz() {console.log('hello'); } baz() {console.log('world'); } } Foo.bar() // helloCopy the code