美文网首页
类和继承

类和继承

作者: 饥人谷_若愚 | 来源:发表于2017-11-19 09:31 被阅读29次
    1. 构造函数
    class Person {
      constructor(name, age) {
        this.name = name;
        this.age = age;
      }
    
      sayHello() {
        console.log( `hello, ${this.name}, i am ${this.age} years old`);
      }
    }
    

    等价于

    function Person(name, age) {
      this.name = name;
      this.age = age;
    }
    
    Person.prototype.sayHello = function () {
      console.log(  `hello, ${this.name}, i am ${this.age} years old`);
    };
    
    var p = new Person('hunger', 2);
    
    1. 静态方法
    class EventCenter {
      static fire() {
        return 'fire';
      }
      static on(){
        return 'on'
      }
    }
    

    等同于

    function EventCenter(){
    }
    EventCenter.fire = function(){}
    EventCenter.on = function(){}
    
    
    1. 继承
    class Person {
      constructor(name, age) {
        this.name = name;
        this.age = age;
      }
    
      sayHello() {
        console.log( `hello, ${this.name}, i am ${this.age} years old`);
      }
    }
    class Student extends Person {
      constructor(name, age, score) {
        super(name, age); 
        this.score = score;
      }
    
      sayScore() {
         console.log(  `hello, ${this.name}, i am ${this.age} years old, i get ${this.score}`);
      }
    }
    

    相关文章

      网友评论

          本文标题:类和继承

          本文链接:https://www.haomeiwen.com/subject/qvtuvxtx.html