面向对象
看这篇的同学,先要学会原型链,若还不会看我的上一篇文章原型链
https://blog.csdn.net/Gueyue/article/details/102545419
类的声明
// 类的声明
function Animal(){
this.name = name
}
// ES6类的声明
class Animal2{
constructor(){
this.name = name
}
}
//实例化
console.log(new Animal('Animal'),new Animal2('Animal2'))
继承
借助原型链实现继承
- 特点:
- 子类的实例也是父类的实例
- 可以方便的基础父类型的原型中的方法,但是属性的继承无意义
- 缺点:
- 只执行一次,无法给属性传值
- 属性的继承无意义
function Person() {
this.name = name
this.age = age
}
Person.prototype.sayHi = function(){
console.log('大家好,我是'+this.name)
}
function Student() {
this.score = 100;
}
Student.prototype = new Person(); //改变prototype的指向
Student.prototype.constructor = Student; //改变构造函数
var s1=new Student()
s1.syHi() //大家好,我是undefined
console.log(s1.age) //undefined
构造继承
-
核心:
-
在子类的内部调用父类,通过call改变父类中this的指向
-
等于是复制父类的实例属性给子类
-
特点:
-
创建子类实例时,可以向父类传递参数
-
可以实现多继承
-
可以方便的继承父类型的属性,但是无法继承原型中的方法
-
缺点:
- 实例并不是父类的实例,只是子类的实例
- 无法继承原型中的方法
- 无法实现函数复用,每个子类都有父类实例函数的副本,影响性能
function Person(name,age){
this.name = name
this.age = age
}
Person.prototype.sayHi = function(){
console.log('大家好,我是'+this.name)
}
function Student(name,age,score){
Person1.call(this,name,age)
this.score = score
}
var s1 = new Student('zs',18,88)
//s1.sayHi() //报错 not a function
console.log(s1 instanceof Person) //false
console.log(s1.name) //zs
组合继承
特点:既是子类的实例,也是父类的实例
可传参
函数可复用
function Person(name,age){
this.name = name
this.age = age
}
Person.prototype.sayHi = function(){
console.log('大家好,我是'+this.name)
}
function Student(name,age,score){
Person1.call(this,name,age)
this.score = score
}
Student.prototype = new Person()
Student.prototype.constructor = Student
var s1 = new Student('zs',18,88)
var s1 = new Student('zs',18,88)
s1.sayHi() //大家好,我是zs
console.log(s1 instanceof Person) //true
console.log(s1.name) //zs
上述构造函数执行了两次并没有必要
可以优化为
function Person(name,age){
this.name = name
this.age = age
}
Person.prototype.sayHi = function(){
console.log('大家好,我是'+this.name)
}
function Student(name,age,score){
Person1.call(this,name,age)
this.score = score
}
Studnet.prototype = Object.create(Person.prototype)
Student.prototype.constructor = Student
var s1 = new Student('zs',18,88)
var s1 = new Student('zs',18,88)
s1.sayHi() //大家好,我是zs
console.log(s1 instanceof Person) //true
console.log(s1.name) //zs