函数的继承

1.通过原型实现继承,改变原型的指向,初始化多个对象时属性值一样

//动物的构造函数
function Animal(name,weight){
	this.name=name;
	this.weight=weight;
}
Animal.prototype.eat=function(){
	console.log("天天吃东西")
}
//狗的构造函数
function Dog(color){
	this.color=color;
}
//改变原型的指向,实现继承
Dog.prototype=new Animal("泰迪","10kg");
//先改变原型指向,再创建新的方法
Dog.prototype.bitePerson=function(){
	console.log("汪汪")
}
var dog=new Dog("黄色");
console.log(dog.name,dog.weight,dog.color)
dog.eat()
dog.bitePerson()

2.借用构造函数实现继承,不能继承方法

//动物的构造函数
function Animal(name,weight){
	this.name=name;
	this.weight=weight;
}
//狗的构造函数
function Dog(name,weight,color){
	//借用构造函数
	Animal.call(this,name,weight)
	this.color=color;
}
var dog=new Dog("泰迪","10kg","黄色");
console.log(dog.name,dog.weight,dog.color)

3.组合继承(改变原型的指向+借用构造函数)

//动物的构造函数
function Animal(name,weight){
	this.name=name;
	this.weight=weight;
}
Animal.prototype.eat=function(){
	console.log("天天吃东西")
}
//狗的构造函数
function Dog(name,weight,color){
	//借用构造函数
	Animal.call(this,name,weight)
	this.color=color;
}
//改变原型指向
Dog.prototype=new Animal();
Dog.prototype.bitePerson=function(){
	console.log("汪汪")
}
var dog=new Dog("泰迪","10kg","黄色");
console.log(dog.name,dog.weight,dog.color)
dog.eat()
dog.bitePerson()

4.拷贝继承,把一个对象中的原型的所有属性和方法复制一份给另一个对象(浅拷贝)

function Animal(){
}
Animal.prototype.name="泰迪"
Animal.prototype.weight="10kg"
Animal.prototype.eat=function(){
	console.log("天天吃东西")
}
var animalObj={}
for(var key in Animal.prototype){
	animalObj[key]=Animal.prototype[key]
}
console.log(animalObj.name,animalObj.weight)
animalObj.eat()

猜你喜欢

转载自blog.csdn.net/weixin_39150852/article/details/85849675