js的继承
Posted 饮尽杯中月
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js的继承相关的知识,希望对你有一定的参考价值。
// 构造函数继承
// 缺点:原型链上的方法和属性没有办法继承
function Person() {
this.name = "person"
this.say = function () {
console.log('say')
}
}
Person.prototype.run = function () {
console.log('run')
}
Person.prototype.hobby = '吃饭'
function Student() {
Person.call(this)
this.age = 19
}
let s1 = new Student()
console.log(s1.hobby)
// 原型链继承
// 缺点:实例化原型对象的属性是引用类型的时候,数据互相受到影响
function Person() {
this.name = "person"
this.arr = [1, 2]
this.say = function () {
console.log('say')
}
}
Person.prototype.run = function () {
console.log('run')
}
Person.prototype.hobby = '吃饭'
function Student() {
this.age = 19
}
Student.prototype = new Person()
let s1 = new Student()
let s2 = new Student()
s1.arr.push(3)
console.log(s1,'s1')
console.log(s2,'s2')
构造函数继承+原型链继承
// 组合式继承
function Person() {
this.name = "person"
this.arr = [1, 2]
this.say = function () {
console.log('say')
}
}
Person.prototype.run = function () {
console.log('run')
}
Person.prototype.hobby = '吃饭'
function Student() {
//构造函数继承
Person.call(this)
this.age = 19
}
//原型链继承
Student.prototype = new Person()
let s1 = new Student()
let s2 = new Student()
s1.arr.push(3)
console.log(s1.hobby, 's1')
console.log(s2, 's2')
待优化
//执行了一次Person
Student.prototype = new Person()
//由于Person.call(this),所以new Student()又执行一次Person
let s1 = new Student()
优化方向:
- 减少Person的执行次数
- Person和Student两个的prototype指向Person的原型对象,所以Student.prototype.constructor是Person的构造函数,所以通过new Student(),其实是通过Person的构造函数来构造实例
- 1的运行不再执行一次Person
- 构造函数指向有问题,s1实例的__proto__的构造函数是Person
- 使得Student的构造函数指向Student
Student.prototype.constructor = Student
-
打印p1发现p1.__proto__constructor指向Student,原因是Student.prototype = Object.create(Person.prototype)使得 Person和Student两个的prototype指向一个原型,所以会相互影响,所以当执行 Student.prototype.constructor = Student的时候,也影响了Person的构造函数
-
将Student的原型对象和Person的原型对象放在同一条原型链上
Student.prototype = Object.create(Person.prototype)
Person
let s1 = new Student
// 组合式继承优化
function Person() {
this.name = "person"
this.arr = [1, 2]
this.say = function () {
console.log('say')
}
}
Person.prototype.run = function () {
console.log('run')
}
Person.prototype.hobby = '吃饭'
function Student() {
Person.call(this)
this.age = 19
}
Student.prototype = Object.create(Person.prototype)
Student.prototype.constructor = Student
let p1 = new Person()
let s1 = new Student()
let s2 = new Student()
s1.arr.push(3)
console.log(s1, 's1')
console.log(s2, 's2')
console.log(p1, 'p1')
以上是关于js的继承的主要内容,如果未能解决你的问题,请参考以下文章