ES5中的继承

2022-12-19  本文已影响0人  男人宫

// 构造函数绑定
   function Animal(){
    this.species = "动物"
   }

   function Cat(name,color){
     Animal.apply(this)
     this.name = name
     this.color = color
   }

  var cat1 = new Cat("小黑","黑色")
  console.log(cat1); 
  /**
   Cat {species: '动物', name: '小黑', color: '黑色'}
  */
  console.log(cat1.species);

  // 第二种prototype模式
     function Animal(){
    this.species = "动物"
   }
   Animal.prototype.eat = function(){
    console.log("爱抓老鼠");
   }
   function Cat(name,color){
     this.name = name
     this.color = color
   }
   //将Cat的prototype对象指向一个Animal的实例
   Cat.prototype = new Animal()
   //经过上一句代码的赋值之后,Cat.prototype.constructor的指向了Animal.不用下面代码改变的话会造成继承链的混乱
   //重新把Cat.prototype.constructor指回自己的构造函数
   Cat.prototype.constructor = Cat 

   var c2 = new Cat("小红","红毛")
   console.log(c2);
   console.log(c2.species);

  //第三种直接继承prototype
  function Animal(){ 
  }
  Animal.prototype.species = "动物";
   function Cat(name,color){
     this.name = name
     this.color = color
   }

  // Cat.prototype = Animal.prototype
  // Cat.prototype.constructor = Cat

  //  var a = new Animal()
  //  console.log(a);

  //  通过打印a可以知道,a的constructor也指向了Cat.
  //为啥会造成上面的现象是因为Cat.prototype = Animal.prototype 
  //修改了Cat.prototype.constructor就等同于修改了Animal.prototype.constructor

  //四 利用Object.create(SuperClass.prototype) 新生成一个原型对象(最终的继承写法)
  //
 //Object.create(Animal.prototype)相当于生成一个{}对象,但这个空对象的prototype和Animal.prototype这个对象
//Vue实例中可以使用Vue中的方法,也是用的这个Object.create绑定的
  Cat.prototype = Object.create(Animal.prototype)
  //修改Cat的constructor不影响Animal的constructor
  Cat.prototype.constructor = Cat
  var a1 = new Animal()
  console.log(a1);
  var c3 = new Cat("小绿","绿毛")
   console.log(c3);

  

  // Object.create()的用法
  /*
  ES5定义了一个名为Object.create()的方法,它创建一个对象,其中第一个参数就是这对个象的原型,
  Object.create()提供第二个可选参数,用以对对象的属性进行进一步描述。  
  */
 var obj1 = Object.create(null) //相当于空对象,任何属性都没
 var obj2 = Object.create({x:1,y:2}) //相当于var obj2 = {}; obj2.prototype = {x:1, y:2}
 var obj3 = Object.create(Object.prototype) //相当于 var obj3 = {}
上一篇 下一篇

猜你喜欢

热点阅读