实现继承的几种方式

(1)寄生继承

Object.create

(2)构造函数+对象冒充

  function Person(_name, _age) {
    
    
      this.name = _name;
      this.age = _name
    }
    Person.prototype.fly = function () {
    
    
      console.log("fly")
    }
    function Student(_name, _age, _job) {
    
    
      Person.call(this, _name, _age)
      this.job = _job
    }
    Student.prototype = new Person()
    var stu = new Student("嘻嘻", 18, "it")
    console.log(stu)

(3)es6的class extends继承

class Person {
    
    
  constructor(_name, _age) {
    
    
    this.name = _name;
    this.age = _age
  }
  fly() {
    
    
    console.log("fly")
  }
}
class Student extends Person {
    
    
  constructor(_name, _age, _job) {
    
    
    super(_name, _age)
    this.job = _job
  }
}
var stu = new Student("嘻嘻", 18, "it")
console.log(stu)
stu.fly()

猜你喜欢

转载自blog.csdn.net/qq_45785424/article/details/108065308