好事总会发生在下个转弯。希望你的愿望都能一一实现。
本文纯属个人理解,学习记录知识的笔记,如有错误请指出,我会及时改正谢谢!!
一.原型和原型链
fuction Player(color) {
this.color = color
}
const whitePlayer = new Player
1.原型就是对象上的属性,就是一对象(prototype),在原型上添加属性和方法的好处(当做构造函数使用时,原型链上挂载的属性和方法会共享到创造的函数中),可以通过a.prototype = {}这种方法进行批量赋值属性和方法(这种方法会将原有属性进行覆盖,一定要对原有属性的检查)
whitePlayer.__proto__ === Player.prototype
Player === Player.prototype.constructor
2.new关键字的过程:1.有一个继承字Player.prototype的新对象被创建 2.this指向被改变指向到新对象3.构造函数值返回如果没有retun则会返回对象,有返回值是基本类型则会返回新对象,有返回值是引用类型则会返回返回值
function mockNew() {
const o = new Object()
const FucntionConstructor = [].shift.call(arguments)
o.___proto__ = FucntionConstructor.protype
const resultObj = FucntionConstructor.apply(o, arguments)
return typeof resultObj === 'object' ?resultObj :o
}
新版本浏览器Object.getPrototypeOf替代__proto__ 三.继承
1.原型链继承
Function Parent() {
this.name = 'parentName
}
Parent.prototype.getName = function() {
console.log(this.name)
}
function Child() {
}
Child.__proto__ = New Parent()
Child.prototype.constructor = Child
缺陷:1·某个属性是引用类型,某个实例修改则会导致所有实例发生变化1.创建child时没法传参
2.构造函数继承
Function Parent() {
this.name = 'parentName
}
Parent.prototype.getName = function() {
console.log(this.name)
}
function Child(id,name,action) {
this.id = id
Parent.call(this,name,action)
}
缺陷:实例公共方法存储地址不同浪费内存
3.组合式继承
Function Parent() {
this.name = 'parentName
}
Parent.prototype.getName = function() {
console.log(this.name)
}
function Child(id,...arg) {
this.id = id
Parent.applay(this,...arg)
}
Child.__proto__ = New Parent()
Child.prototype.constructor = Child
缺陷:Parent函数被调用了两次
4.寄生组合式继承
Function Parent() {
this.name = 'parentName
}
Parent.prototype.getName = function() {
console.log(this.name)
}
function Child(id,...arg) {
this.id = id
Parent.applay(this,...arg)
}
Child.prototype = Object.creat(Parent.prototype)
Child.prototype.constructor = Child
5.class继承
class Parent() {
constructor() {
this.name = 'parentName'
}
getName() {
console.log(this.name)
}
}
class Child extends Parent {
constructor() {
super()
}
}