JS继承一个类

1,使用一个中间类实现猫继承动物

 var Animate=function(){
     this.name="动物"
 }
Animate.prototype.say=function(){
    console.log("喵")
}

var Cat=function(){
   Animate.apply(this,arguments)
}
//使用一个临时的类,使这个类prototype指向Animate的prototype
function foo(){}
foo.prototype=Animate.prototype
//Cat继承这个foo类
Cat.prototype=new foo()
Cat.prototype.constructor=Cat
var cat=new Cat()

打印出来:

JS继承一个类_第1张图片
图片.png

2,不使用类也能实现继承(对象之间的继承)

function extend(parent){
   var empty=function(){}
   empty.prototype=parent
  return empty
}
var Animate={
  name:"动物",
  say:function(){
  console.log("动物叫")
  }
}
var cat=new extend(Animate)
cat.say=function(){
console.log("喵喵喵")
}

3,IE不支持的写法

 var Animate={
    name:"动物",
    say:function(){
    console.log("动物叫")
  }
}
var cat=Object.create(Animate.prototype)
cat.say=function(){
    console.log("喵喵喵")
}

打印结果:

JS继承一个类_第2张图片
图片.png

你可能感兴趣的:(JS继承一个类)