原型继续和 Class 继续
原型怎样完成继续?Class 怎样完成继续?Class 实质是什么?
起首先来说下 class,其实在 JS 中并不存在类,class 只是语法糖,实质照样函数。
那让我们来完成一下继续
组合继续
组合继续是最经常运用的继续体式格局,
function Parent(value) {
this.val = value
}
Parent.prototype.getValue = function() {
console.log(this.val)
}
function Child(value) {
Parent.call(this, value)
}
Child.prototype = new Parent()
const child = new Child(1)
child.getValue() // 1
child instanceof Parent // true
以上继续的体式格局中心是在子类的组织函数中经由过程 Parent.call(this) 继续父类的属性,然后转变子类的原型为 new Parent() 来继续父类的函数。
这类继续体式格局长处在于组织函数能够传参,不会与父类援用属性同享,能够复用父类的函数,然则也存在一个瑕玷就是在继续父类函数的时刻挪用了父类组织函数,致使子类的原型上多了不需要的父类属性,存在内存上的糟蹋。
寄生组合继续
function Parent(value) {
this.val = value
}
Parent.prototype.getValue = function() {
console.log(this.val)
}
function Child(value) {
Parent.call(this, value)
}
Child.prototype = Object.create(Parent.prototype, {
constructor: {
value: Child,
enumerable: false,
writable: true,
configurable: true
}
})
const child = new Child(1)
child.getValue() // 1
child instanceof Parent // true
以上继续完成的中心就是将父类的原型赋值给了子类,而且将组织函数设置为子类,如许既处理了无用的父类属性题目,还能准确的找到子类的组织函数。
Class 继续
class Parent {
constructor(value) {
this.val = value
}
getValue() {
console.log(this.val)
}
}
class Child extends Parent {
constructor(value) {
super(value)
this.val = value
}
}
let child = new Child(1)
child.getValue() // 1
child instanceof Parent // true
class 完成继续的中心在于运用 extends 表明继续自哪一个父类,而且在子类组织函数中必需挪用 super,由于这段代码能够算作 Parent.call(this, value)。
模块化
为何要运用模块化?都有哪几种体式格局能够完成模块化,各有什么特性?
- 处理定名争执
- 进步代码的可复用性
- 进步代码的可维护性
马上实行函数
以作用域的体式格局来处理定名争执的题目
Module
// 引入模块 API
import XXX from './a.js'
import { XXX } from './a.js'
// 导出模块 API
export function a() {}
export default function() {}
Proxy
Proxy 能够完成什么功用?
Proxy 是 ES6 中新增的功用,它能够用来自定义对象中的操纵。