面向对象三大特征:
一、 封装:隐藏内部的细节,不暴露在外面(不让其它访问仅能自己访问)
//在js中利用函数的作用域来模拟
// 封装
let Pet=function (name,types) {
this.name=name;
//封装,将变量用一个关键字声明,这样外面就不能访问了
let _types=types;
};
//将相同的方法或属性放在原型链上,方便代码的复用
Pet.say=function(){
return `hello!我叫:${this.name},我是一只可爱的${this._types}`;
};
console.log(Pet.say());//hello!我叫:Pet,我是一只可爱的undefined
二、继承:子类继承父类,就可拥有父类的属性和方法//在js中利用对象冒充(父类构造函数去充当子类的属性)的方式实现继承
//方法1:在js中利用对象冒充(父类构造函数去充当子类的属性)的方式实现继承
//继承
let Pet=function (name,types) {
this.name=name;
this.types=types;
};
let Dog=function(name,types,colors,age){
this.colors=colors;
this.age=age;
this.temp=Pet;//将Pet构造函数赋值给temp,充当Dog的子类
this.temp(name,types);//调用其构造函数并赋值
delete this.temp;//此时temp已经无用了,将其删除
}
let taidi=new Dog("泰迪","小狗","土其色",2);
console.log(taidi.name+" "+taidi.types+" "+taidi.colors+" "+taidi.age);//泰迪 小狗 土其色 2
//方法2:使用方法借用的方式实现继承
let Pet=function (name,types) {
this.name=name;
this.types=types;
};
let Dog=function(name,types,colors,age){
//借用Pet的方法
//Pet.apply(this,[name,types]);
Pet.call(this,name,types);
this.colors=colors;
this.age=age;
}
let taidi=new Dog("泰迪","小狗","土其色",2);
console.log(taidi.name+" "+taidi.types+" "+taidi.colors+" "+taidi.age);//泰迪 小狗 土其色 2
//方法3:最终,js采用了原型链继承的方式
//采用了原型链继承的方式
let Pet=function (name,types) {
this.name=name;
this.types=types;
};
//给Pet原型链上添加一个方法
Pet.prototype.say=function(){
return `hello!大家好我是smallzz`;
}
let Dog=function(name,types,colors,age){
//借用Pet的方法
//Pet.apply(this,[name,types]);
Pet.call(this,name,types);
this.colors=colors;
this.age=age;
};
//将Pet的构造函数放在Dog的原型链上
Dog.prototype=new Pet();
let taidi=new Dog("泰迪","小狗","土其色",2);
console.log(taidi.name+" "+taidi.types+" "+taidi.colors+" "+taidi.age);//泰迪 小狗 土其色 2
console.log(taidi.say());//hello!大家好我是smallzz
方法4:ES6提供了extends关键字
//使用extends实现继承
class Pet{
constructor(name,types){
this.name=name;
this.types=types;
}
say(){
return `hello!大家好我是smallzz`;
}
}
class Dog extends Pet{ //继承Pet
constructor(name,types,colors,age){
super(name,types);//调用父类的构造器
this.colors=colors;
this.age=age;
}
}
let taidi=new Dog("泰迪","小狗","土其色",3);
console.log(taidi.name+" "+taidi.types+" "+taidi.colors+" "+taidi.age);//泰迪 小狗 土其色 3
console.log(taidi.say());//hello!大家好我是smallzz
三、多态:定义:同一操作用于不同的对象上,会产生不同的结果。js中的对象天生就是多态的
PS:方法借用