当前位置:网站首页>The difference between Es5 class and ES6 class

The difference between Es5 class and ES6 class

2020-11-06 01:16:25 Tang Dynasty_ silver

stay es5 The main way to define a class is through constructor and prototype , stay es6 We can pass class To define a class , Sort out the differences today .

About es5 How to define classes in , You can read this article Js Of ‘ class ’, We mainly talk about es5 Classes and es6 in class Class differences .

One 、class Class must new call , Not directly .


class Class execution will report an error , and es5 There is no essential difference between a class in and a normal function , Execution must be ok Of .

Two 、class Class does not have variable Promotion


chart 2 Report errors , explain class Method does not raise the definition of a class to the top .

3、 ... and 、class Class cannot traverse properties and methods on its instance prototype 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) {
    //  Archetype like It's also printed out 
    console.log(key)  // color、like
}
class Foo {
    constructor (color) {
        this.color = color
    }
    like () {
        console.log(`like${this.color}`)
    }
}
let foo = new Foo('red')

for (let key in foo) {
    //  Just print one color, There is no print on the prototype chain like
    console.log(key)  // color
}

Four 、new.target attribute

es6 by new The command introduces one new.target attribute , It will be returned new The constructor on which the command operates . If not through new Call or Reflect.construct() Called ,new.target Returns the undefined

function Person(name) {
  if (new.target === Person) {
    this.name = name;
  } else {
    throw new Error(' You have to use  new  Command generation instance ');
  }
}

let obj = {}
Person.call(obj, 'red') //  In this case, use non new Will report an error when calling 

5、 ... and 、class Like static Static methods

static Static methods can only be called through classes , It doesn't show up in instances ; In addition, if the static method contains this keyword , This this Refers to the class , Not an instance .static Declared static properties and methods can be inherited by subclasses .

class Foo {
  static bar() {
    this.baz(); //  Here this Pointing class 
  }
  static baz() {
    console.log('hello'); //  It doesn't appear in the instance 
  }
  baz() {
    console.log('world');
  }
}

Foo.bar() // hello

版权声明
本文为[Tang Dynasty_ silver]所创,转载请带上原文链接,感谢