面向对象的三大特征
封装:在好书内部作用域中声明一个变量,只能内部访问到、
继承:1.对象冒充
代码实现
const Person = function (name, age) {
this.name = name;
this.age = age;
}
Person.prototype.test = "this is a test";
const Student = function (name, age, gender, score) {
this.temp = Person; // 用一个变量来传递
this.temp(name, age); //
delete this.temp; // 传递完成,删除变量
this.gender = gender;
this.score = score;
}
const stu= new Student("小明", 18, "男", 100);
console.log(stu.name); // 小明
console.log(stu.score); // 100
缺点:不能继承到原型对象上的属性和方法
console.log(xiejie.test); // undefined
2.方法借用: call和apply
代码实现
let obj={
name:"小明"
, say:function(){
console.log(`${this.name}`)
}
}
let obj2={
name:"李华"
}
obj.say.call(obj2)
- 原型继承
代码实现
const Person = function (name, age) {
this.name = name;
this.age = age;
}
Person.prototype.test =function(){
console.log("这是Person")
}
const Student=function(name,age,gender,score){
Person.apply(this,[name,age])/*借用Person的构造函数添加name和age this指向Student*/
this.gender=gender;
this.score=score;
}
Student.prototype=new Person();/*改变原型对象的指向*/
const stu= new Student("小明", 18, "男", 100);
console.log(stu.test()) //这是Person
多态: Js的多态是天生的(因为不用传参数的类型)
代码实现
const Animal=function(animal){
animal.say()
}
const duck={
name:"鸭",
say:function(){
console.log(`${this.name}:嘎嘎嘎`)
}
}
const chicken={
name:"鸡",
say:function(){
console.log(`${this.name}:咯咯咯`)
}
}
new Animal(chicken)//鸡:咯咯咯
new Animal(duck)//鸭:嘎嘎嘎