修飾器@
只能用于類 和 類的方法
類的修飾器
@testable
class MyTest {
}
// target 指向修飾的類
function testable(target) {
target.isTestable = true
}
MyTest.isTestable // true
@decorator
class A {}
//等同于
class A {}
A = decorator(A) || A
修飾器對類的行為的改變,是代碼編譯時發(fā)生的,而不是在運行時
// mixins.js 可以返回一個函數(shù)
export function mixins(...list) {
return function(target) {
Object.assign( target.prototype, ...list )
}
}
// main.js
import { mixins } from './mixins.js'
const Foo = {
foo() {console.log('foo')}
}
@mixins(Foo) // 當函數(shù)調(diào)用,傳入?yún)?shù)
class MyClass {}
let obj = new MyClass()
obj.foo // 'foo'
方法的修飾
class Person {
@readonly
name() { return `${this.first}${this.last}` }
}
readonly 修飾類的 name 方法
// 接收三個參數(shù)
// target 修飾的目標對象,即是類的實例
// name 修飾的屬性名
// descriptor 該屬性的描述對象
function readonly( target, name, descriptor ) {
// descriptor對象原來的值: {
// value: ...;enumerable: false,configurable: true, writable: true
//}
descriptor.writable = false
return descriptor
}
readonly( Person.prototype, 'name', descriptor )
//類似與
Object.defineProperty( Person.prototype, 'name', descriptor )
// log 打印日志
class Math {
@log
add(a,b) {
return a + b
}
}
function log( target, name, descriptor ) {
var oldValue = descriptor.value
descriptor.value = function () {
console.log(`calling "${name}" width`, arguments)
return oldValue.apply(null, arguments)
}
return descriptor
}
const math = new Math()
math.add( 2, 3 )
Mixin 混入
- Object.assgin()
export function mixins(...list) {
retrun function ( target ) {
Object.assign( target.prototype, ...list )
}
}
會改寫 類的prototype 對象
- 類的繼承 實現(xiàn)一個中間類
let Mixin = ( superClass ) => class extends superClass {
foo(){
...
}
}