JavaScript es6新语法class

2020-04-01  本文已影响0人  1CC4

在没有es6带来的class的时候,编写JavaScript的时候很多时候会通过构造函数和原型链来添加方法属性,实现class的功能。

一、类

// 构造函数
        function Person(name, age) {
            this.name = name;
            this.age = age;
            this.sayName = function () {
                console.log("name", this.name)
            }
        }
// 原型方法
        Person.prototype.getName = function(){
            return this.name;
        }
class Person {
  constructor(name, age) {  // 构造函数
    this.name = name;
    this.age = age;
  }
  getName() {   // 这种写法表示将方法添加到原型中
    return this.name
  }
  static a = 20;  // 等同于 Person.a = 20
  c = 20;   // 表示在构造函数中添加属性 在构造函数中等同于 this.c = 20
// 箭头函数的写法表示在构造函数中添加方法,在构造函数中等同于this.getAge = function() {}
  getAge = () => this.age   
}

二、继承extends

class Student extends Person{
    constructor(name,age){
        super(name,age); //调父类Person类构造函数
    }
}

const stu1 = new Student('张三',12);
stu1.sayhi();

只需要一个extends关键字,就可以实现继承了,不用像ES5那样去担心构造函数继承和原型继承,除此之外,我们还需要关注一个叫做super的方法。

super还可以直接调用父级的原型方法

// 构造函数中
// es6 
super(name, age);

// es5
Person.call(this);
上一篇 下一篇

猜你喜欢

热点阅读