JS中的继承

继承是面向对象思想中的重要概念,继承是类和类之间的关系,它使得子类具有了父类别的各种属性和方法。而 JavaScript 中没有类的概念,那么我们要写出继承,还得先写一个类,那么类到底是什么呢:能产生对象的东西即为类。

JS中的继承

es5写法

function Human(name){
     this.name = name
 }
 Human.prototype.run = function(){
     console.log("我叫"+this.name+",我在跑")
     return undefined
 }

 function Man(name){
     Human.call(this, name)
     this.gender = '男'
 }
 Man.prototype.__proto__ = Human.prototype
 Man.prototype.fight = function(){
     console.log('糊你熊脸')
 }

 // 由于ie不兼容性__proto__
 Man.prototype.__proto__ = Human.prototype
 // 转换为
 var f = function(){}
 f.prototype = Human.prototype
 Man.prototype = new f()

es6的写法

class Human{
     constructor(name){
         this.name = name
     }
     run(){
         console.log("我叫"+this.name+",我在跑")
         return undefined
     }
 }
 class Man extends Human{
     constructor(name){
         super(name)
         this.gender = '男'
     }
     fight(){
         console.log('糊你熊脸')
     }
 }

es5写法 和 es6写法 的区别

class 后面写 extends 再接着写你的父类,用extends连上原型链,这里等价于 Man.prototype.__proto__ = Human.prototype
super(name) 对应 Human.call(this, name),表示调用 Human,这样去调用你的父类的构造函数,让他把 name 填一下。

你可能感兴趣的:(JS中的继承)