es5继承

作者: Wrestle_Mania | 来源:发表于2019-11-21 21:49 被阅读0次
    • 对象冒充实例继承(无法获取原型链上的属性和方法
    function Person(name, age) {
      this.name = name;
      this.age = age;
      this.run = function() {
        console.log(`${this.name}--${this.age}`);
      };
    }
    
    Person.prototype.sex = "男";
    Person.prototype.work = function() {
      console.log(`${this.name}的性别是${this.sex}`);
    };
    
    // 对象冒充实例继承
    // 能继承构造函数中的属性和方法,但是不能继承原型链上的属性和方法
    function Web(name, age) {
      Person.call(this, name, age);
    }
    
    const web = new Web("JonSnow", 21);
    
    console.log(web.name); //JonSnow
    console.log(web.sex); //undefined
    web.run();
    web.work(); //报错
    
    • 原型链继承(实例化无法给父类传参
    function Person(name, age) {
      this.name = name;
      this.age = age;
      this.run = function() {
        console.log(`${this.name}--${this.age}`);
      };
    }
    
    Person.prototype.sex = "男";
    Person.prototype.work = function() {
      console.log(`${this.name}的性别是${this.sex}`);
    };
    
    function Web(name, age) {}
    
    Web.prototype = new Person();
    
    const web = new Web("JonSnow", 21);
    
    console.log(web.name); //undefined
    console.log(web.sex); //男
    web.run(); //undefined--undefined
    web.work(); //undefined的性别是男
    
    
    • 二者结合,实现继承
    function Person(name, age) {
      this.name = name;
      this.age = age;
      this.run = function() {
        console.log(`${this.name}--${this.age}`);
      };
    }
    
    Person.prototype.sex = "男";
    Person.prototype.work = function() {
      console.log(`${this.name}的性别是${this.sex}`);
    };
    
    function Web(name, age) {
      Person.call(this, name, age);
    }
    
    Web.prototype = new Person();
    
    const web = new Web("JonSnow", 21);
    
    console.log(web.name); //JonSnow
    console.log(web.sex); //男
    web.run(); //JonSnow--JonSnow
    web.work(); //JonSnow的性别是男
    

    相关文章

      网友评论

          本文标题:es5继承

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