不使用 class 如何实现继承

248 阅读1分钟

原型式继承

function Animal(color){
     this.color = color
 }
 Animal.prototype.move = function(){
 	console.log("I can move")
 } 
 function Dog(color, name){
     Animal.call(this, color) // 或者 Animal.apply(this, arguments)
     /*
     call 方法可以更改函数的作用环境,在子类中对 Animal 调用 call 方法
     是将子类中的变量在父类中执行一遍,父类中是给 this 绑定属性的,
     子类继承了父类的共有属性
     */
     this.name = name
 }



 // 下面三行实现 Dog.prototype.__proto__ = Animal.prototype
 function temp(){}
 temp.prototype = Animal.prototype
 Dog.prototype = new temp()

 Dog.prototype.constuctor = Dog // 解决 dog 实例 constructor 指向不正确问题
 Dog.prototype.say = function(){ console.log('汪')}

 const dog = new Dog('黄色','阿黄')

skylinebin.com//JavaScript…