手写继承(类与函数)

97 阅读1分钟

类继承

class Animal {
	constructor(color) {
    	this.color = color
    }
    move() {
    	//...
    }
}

class Dog extends Animal{
	constructor(color,name) {
   		super(color)
        this.name = name
    }
    say() {
    	//...
    }
}

函数的继承

function Animal(color) {
	this.color = color
}
Animal.prototype.move = function(){}

function Dog(color,name) {
	Animal.apply(this,arguments)
   	this.name = name
}
// 构造函数Dog的原型对象上先不要添加say方法,后面我们先给他一个空的对象当原型,然后再添加say方法在上面

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

Dog.prototype.say = function() {}