JS继承和多态
- 继承
案例:创建一只狗
function Dog({name,type,age}){
//this = new Object();
//添加属性
this.name = name;
this.type = type;
this.age = age;
}
/*
通过构造函数的原型添加方法
*/
Dog.prototype = {
run: function(){
alert(this.name + "会飞快的奔跑");
},
showSelf: function(){
alert(`这是一个${this.type}的,${this.age}岁的,${this.name}叫的小狗`);
}
}
/*
分类更加细分的构造函数。
*/
function Teddy({name,type,age,color}){
//1.继承父一级构造函数所有的属性
//构造函数的伪装
Dog.call(this,{
name: name,
type: type,
age: age
})
//添加自己的属性
this.color = color;
}
// 2.原型链 继承父一级的方法
//<1>通过for...in遍历继承
for(var funcName in Dog.prototype){
Teddy.prototype[funcName] = Dog.prototype[funcName];
}
//<2>Object.create()
Teddy.prototype = Object.create(Dog.prototype);
//<3>调用构造函数继承
Teddy.prototype = new Dog({});
var xiaohong = new Teddy({
name: "小红",
type: "泰迪",
age: 10,
color: "红色"
})
alert(xiaohong.name); // 小红
alert(xiaohong.age); // 10
alert(xiaohong.type); // 泰迪
alert(xiaohong.color); // 红色
xiaohong.showSelf(); // 这是一个泰迪的,10岁的,小红叫的小狗
拓展:对象拷贝
var obj1 = {
a: 10,
b: 20,
c: 30
};
var obj2 = obj1;
obj2.c = 100;
console.log(obj1); // {a: 10,b: 20,c: 100}
console.log(obj2); // {a: 10,b: 20,c: 100}
var obj1 = {
a: 10,
b: 20,
c: 30
};
var obj2 = {};
for(var attr in obj1){
obj2[attr] = obj1[attr];
}
obj2.c = 100;
console.log(obj1); // {a: 10,b: 20,c: 30}
console.log(obj2); // {a: 10,b: 20,c: 100}
- 多态
案例:创建一只狗
function Dog({name,type,age}){
//this = new Object();
//添加属性
this.name = name;
this.type = type;
this.age = age;
}
/*
通过构造函数的原型添加方法
*/
Dog.prototype = {
run: function(){
alert(this.name + "会飞快的奔跑");
},
showSelf: function(){
alert(`这是一个${this.type}的,${this.age}岁的,叫${this.name}的小狗`);
}
}
/*
分类更加细分的构造函数。
*/
function Teddy({name,type,age,color}){
//1.继承父一级构造函数所有的属性
//构造函数的伪装
Dog.call(this,{
name: name,
type: type,
age: age
})
//添加自己的属性
this.color = color;
}
//继承父类方法
for(var funcName in Dog.prototype){
Teddy.prototype[funcName] = Dog.prototype[funcName];
}
// 新增子方法
Teddy.prototype.showColor = function(){
alert(this.color);
}
//在子一级构造函数重写showSelf()方法
Teddy.prototype.showSelf = function(){
alert(`这是一个${this.type}的,${this.age}岁的,是${this.color}的,叫${this.name}叫的小狗`);
}
var xiaohong = new Teddy({
name: "小红",
type: "泰迪",
age: 10,
color: "红色"
});
xiaohong.showSelf(); // 这是一个泰迪的,10岁的,是红色的,叫小红叫的小狗
var xiaohei= new Dog({
name: "小黑",
type: "柴犬",
age: 5
});
xiaohei.showSelf(); // 这是一个柴犬的,5岁的,叫小黑的小狗
总结:
继承和多态同一件事情的两种完全不同的侧重:
继承:侧重的是从父一级构造函数,继承到的属性和方法
多态:侧重的是子一级,自己重写和新增的属性和方法