实现javascript的继承

1. ES6的extends

使用extends 关键字实现类之间的继承。这比在ES5中使用继承要方便很多。

//定义类父类
class Animal {
    
       
  constructor(color) {
    
       
    this.color = color;   
  }   
  greet(sound) {
    
       
    console.log(sound);   
  }  
}   
class Dog extends Animal {
    
       
  constructor(color) {
    
       
    super(color);   
    this.color = color;   
  }  
}   

let dog = new Dog('黑色');  
dog.greet('汪汪');  // "汪汪"
console.log(dog.color); // "黑色"


2. 利用原型和call

   const extend = (Target, Origin) => {
    
    
           // Origin.call(Target)
            function Fun() {
    
     }
            Fun.prototype = Origin.prototype
            Target.prototype = new Fun()
            //Target.prototype = Object.create(Origin.prototype)
            Target.prototype.constructor = Target
            Target.prototype.uber = Origin.prototype
        }
        Father.prototype.b = 1
        function Father() {
    
    
            this.a=2
        }

        function Son() {
    
    
            // Father.call(this)
        }
        extend(Son, Father)
        var son = new Son();
        var father = new Father();
        console.log(son.b)
        console.log(son.a)

3. 寄生组合式继承

function Animal(color) {
    
    
  this.color = color;
  this.name = 'animal';
  this.type = ['pig', 'cat'];
}
Animal.prototype.greet = function(sound) {
    
    
  console.log(sound);
}
function Dog(color) {
    
    
  Animal.apply(this, arguments);
  this.name = 'dog';
}
/* 注意下面两行 */

Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.getName = function() {
    
    
  console.log(this.name);
}
var dog = new Dog('白色');   
var dog2 = new Dog('黑色');     
dog.type.push('dog');   
console.log(dog.color);   // "白色"
console.log(dog.type);   // ["pig", "cat", "dog"]
console.log(dog2.type);  // ["pig", "cat"]
console.log(dog2.color);  // "黑色"
dog.greet('汪汪');  //  "汪汪"


Object.create()的浅拷贝的作用类式下面的函数:

function create(obj) {
    
    
  function F() {
    
    };
  F.prototype = obj;
  return new F();
}

这里还需注意一点,由于对Animal的原型进行了拷贝后赋给Dog.prototype,因此Dog.prototype上的constructor属性也被重写了,所以我们要修复这一个问题:Dog.prototype.constructor = Dog;

运用闭包私有化变量的写法

const inherit = (() => {
    
    
    let F = function () {
    
    }
    return (Target,Origin) => {
    
    
        F.prototype= Origin.prototype
        Target.prototype = new F()
        Target.prototype.constructor = Target
        Target.prototype.uber = Origin.prototype
    }
})()

继承全面分析

猜你喜欢

转载自blog.csdn.net/pz1021/article/details/105150115
今日推荐