js继承方式,面试常考?

继承常用主要分为以下几部分,构造,原型,实例,组合,class,下面具体代码进行分析与展示:

一、构造继承,关键词call

 1  function Animal(name) {
 2       this.name = name;
 3       this.sleep = function () {
 4          return this.name + '正在睡觉';
 5       }
 6    }
 7 
 8    Animal.prototype.eat = function (food) {
 9       return this.name + '正在吃:' + food;
10    }
11 
12    function Cat(name) {
13       Animal.call(this);
14       this.name = name;
15    }
16 
17    var cat = new Cat('Tom');
18    console.log(cat);

二、原型继承,关键词:prototype

 1 function Animal(name) {
 2       this.name = name;
 3       this.sleep = function () {
 4          return this.name + '正在睡觉';
 5       }
 6    }
 7 
 8    Animal.prototype.eat = function (food) {
 9       return this.name + '正在吃:' + food;
10    }
11 
12    function Cat() {}
13 
14    Cat.prototype = new Animal();
15    Cat.prototype.name = 'cat';
16    Cat.prototype.constructor = Animal();
17 
18    var cat = new Cat();
19    console.log(cat)

三、实例继承,关键词,new 实例()

 1 function Animal(name) {
 2       this.name = name | "Tom";
 3       this.sleep = function () {
 4          return this.name + '正在睡觉';
 5       }
 6    }
 7 
 8    Animal.prototype.eat = function (food) {
 9       return this.name + '正在吃:' + food;
10    }
11 
12    function Cat(name) {
13       var instance = new Animal();
14       instance.name = name || 'Tom';
15       return instance;
16    }
17 
18    var cat = new Cat();
19    console.log(cat);

四、组合继承,构造继承+原型继承,关键词:call,prototype

 1 function Animal(name) {
 2       this.name = name;
 3       this.sleep = function () {
 4          return this.name + '正在睡觉';
 5       }
 6    }
 7 
 8    Animal.prototype.eat = function (food) {
 9       return this.name + '正在吃:' + food;
10    }
11 
12    function Cat(name) {
13       Animal.call(this);
14       this.name = name || 'Tom';
15    }
16    Cat.prototype = new Animal();
17 
18    var cat = new Cat('Tom');
19    console.log(cat);

五、class继承,编译后就是组合继承,关键词es6

 1  class Animal {
 2       constructor(name) {
 3          this.name = name || 'Animal';
 4          this.sleep = function () {
 5             return this.name + ' 正在睡觉 ';
 6          }
 7       }
 8 
 9       eat(food) {
10          return this.name + ' 正在吃 ' + food;
11       }
12    }
13 
14    class Cat extends Animal {
15       constructor(name, age) {
16          super(name);
17          this.age = age;
18       }
19 
20       eat(food) {
21          const result = super.eat(food);
22          return this.age + ' 岁的 ' + result;
23       }
24    }
25 
26    const cat = new Cat('Tom', 3);
27    console.log(cat);

 

posted @ 2020-09-15 11:03  程序員劝退师  阅读(377)  评论(0编辑  收藏  举报