以前的 JS 面向对象机制

  • 以前的 JS 是通过prototype来实现面向对象以及继承的
  • 比如:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    function User(name,age) {
    this.name = name;
    this.age = age;
    }
    User.prototype.showName = function(){
    alert(this.name);
    }
    User.prototype.showAge = function(){
    alert(this.age);
    }
    function VipUser(name,age,level) {
    User.call(this,name,age);
    this.level = level;
    }
    VipUser.prototype = new User();
    VipUser.prototype.constructor = VipUser;
    VipUser.prototype.showLevel = function(){
    alert(this.level);
    };
  • ES6中新增了class关键字,构造器和类分开了,class里面直接加方法

  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    class User {
    constructor(name,age){
    this.name = name;
    this.age = age;
    }
    showName(){
    alert(this.name);
    }
    showAge(){
    alert(this.age);
    }
    }
    let user = new User('刘浩',23);
    user.showName();
    user.showAge();

    class vipUser extends User{
    constructor(name,age,level){
    super(name,age);
    this.level = level;
    }
    showLevel(){
    alert(this.level);
    }
    }
    let vipu = new vipUser('xiaoming',324,2);
    vipu.showName();
    vipu.showAge();
    vipu.showLevel();