Es6的面向对象和继承写法是什么样子的?

传统的js的面向对象和继承是很恶心的,实际上在es6之前,官方是没有提供继承的方法的。都是民间艺术家自己折腾的。

原始的js对象和继承的写法

声明
    function Person(name, age) {
       this.name = name;
       this.age = age;
     }
     Person.prototype.showName = function() {
      console.log(`我是${this.name}`);
     }
     Person.prototype.showAge = function() {
       console.log(`我今年${this.age}岁`);
     }
     let p = new Person('simoon', 28)
     p.showName();
     p.showAge();
继承
    function Worke(job, name, age) {
      Person.call(this, name, age)
      this.job = job;
    }
    Worke.prototype = new Person();
    Worke.prototype.showJob = function() {
      console.log("我的工作是: " + this.job);
    }

    let w = new Worke('打杂的', 'simoon', 18);
    w.showJob();

备注:如有必要还要手动调整constructor属性。

看看es6的写法吧

ps: 好吧,天下语言一大抄。。

声明
    class Person{
      constructor(name, age) {
        this.name = name;
        this.age = age;
      }
      showName() {
        console.log(this.name);
      }
      showAge() {
        console.log(this.age);
      }
    }
继承
    class Worker extends Person{
      constructor(name, age, job) {
        super(name, age);
        this.job = job;
      }
      showJob() {
        console.log(this.job);
      }
    }

    let w = new Worker('花花', 2, 'work')

    w.showName();
    w.showAge();
    w.showJob();

到此为止。留个记录。

猜你喜欢

转载自blog.csdn.net/weixin_40814356/article/details/81609824