目录
原型:每个函数都会创建一个prototype属性,在原型对象上定义的属性和方法可被对象实例共享
链表 :
原型链继承 Child.prototype = new Father()
/**************原型链继承 引用值共享*********************/
//子类原型指向父类实例
function Father() {
this.name = 'lily';
this.arr = [1, 2, 3, 4]
}//构造函数
Father.prototype.getName = function () {
return this.name
}
function Child() { }
Child.prototype = new Father()
const f1 = new Child()//实例
const c2 = new Child()
f1.name = 'John'
f1.arr.push(5)
console.log('f1', f1, f1.getName())
console.log('c2', c2, c2.getName())
缺点: 引用值共享
构造函数继承 Father.call(this)
/*************构造函数继承 拿不到原型上的方法**********************/
//子类构造函数中执行父类构造函数,并绑定子类this
function Father() {
this.name = 'lily';
this.arr = [1, 2, 3, 4]
}
Father.prototype.getName = function () {
return this.name
}
function Child() {
Father.call(this)
}
const f1 = new Child()
const c2 = new Child()
f1.name = 'John'
f1.arr.push(5)
console.log('f1', f1)
console.log('c2', c2)
缺点:拿不到原型上的方法
组合式继承 (原型链+构造函数)
/*************组合式继承**********************/
function Father() {
this.name = 'lily';
this.arr = [1, 2, 3, 4]
}
Father.prototype.getName = function () {
return this.name
}
function Child() {
Father.call(this)//第二次调用 Father()
}
Child.prototype = new Father()//第一次调用 Father()
Child.prototype.constructor = Child
const f1 = new Child()
const c2 = new Child()
f1.name = 'John'
f1.arr.push(5)
console.log('f1', f1, f1.getName())
console.log('c2', c2, c2.getName())
缺点:父类构造函数被调用两次
寄生组合式继承
Child.prototype = Object.create(Father.prototype)
/*************寄生组合式继承**********************/
function Father() {
this.name = 'lily';
this.arr = [1, 2, 3, 4]
}
Father.prototype.getName = function () {
return this.name
}
function Child() {
Father.call(this)//绑定Father
}
//Object.create()原型式继承,浅拷贝
Child.prototype = Object.create(Father.prototype)
Child.prototype.constructor = Child
const f1 = new Child()
const c2 = new Child()
f1.name = 'John'
f1.arr.push(5)
console.log('f1', f1, f1.getName())
console.log('c2', c2, c2.getName())
class
/*************ES6 class**********************/
class Father {
constructor() {
this.name = 'lily';
this.arr = [1, 2, 3, 4]
}
}
Father.prototype.getName = function () {
return this.name
}
class Child extends Father {
constructor() {
super()
}
}
const f1 = new Child()
const c2 = new Child()
f1.name = 'John'
f1.arr.push(5)
console.log('f1', f1, f1.getName())
console.log('c2', c2, c2.getName())