返回

es5和es6中的类比较,揭开语法糖的秘密

前端

es5中的类和es6中的类

在es5中,类主要通过构造函数和原型两种方式来定义。构造函数用于创建类的实例,原型用于定义类的属性和方法。es6中引入了class,可以直接定义一个类,而不需要构造函数和原型。

es5中的类定义方式

function Person(name) {
  this.name = name;
}

Person.prototype.greet = function() {
  console.log(`Hello, my name is ${this.name}.`);
};

es6中的类定义方式

class Person {
  constructor(name) {
    this.name = name;
  }

  greet() {
    console.log(`Hello, my name is ${this.name}.`);
  }
}

es5中的类继承方式

在es5中,类的继承可以通过原型链来实现。子类继承父类的原型,从而获得父类的方法和属性。

function Parent() {
  this.name = "parent";
}

Parent.prototype.greet = function() {
  console.log(`Hello, my name is ${this.name}.`);
};

function Child() {
  this.name = "child";
}

Child.prototype = new Parent();

const child = new Child();

child.greet(); // Hello, my name is child.

es6中的类继承方式

在es6中,类的继承可以通过extends关键字来实现。子类继承父类的所有方法和属性。

class Parent {
  constructor(name) {
    this.name = name;
  }

  greet() {
    console.log(`Hello, my name is ${this.name}.`);
  }
}

class Child extends Parent {
  constructor(name) {
    super(name);
  }
}

const child = new Child("child");

child.greet(); // Hello, my name is child.

es5中的类实例化方式

在es5中,类的实例化可以通过new关键字来实现。new关键字创建一个类的实例,并将类的构造函数作为参数传入。

const person = new Person("John");

person.greet(); // Hello, my name is John.

es6中的类实例化方式

在es6中,类的实例化也可以通过new关键字来实现。new关键字创建一个类的实例,并将类的构造函数作为参数传入。

const person = new Person("John");

person.greet(); // Hello, my name is John.

总结

es5和es6中的类在语法、定义方式、继承方式、实例化方式等方面都存在差异。es6中的类更加简洁、清晰,更符合现代编程语言的设计理念。