js:类的装饰器基本用法
JS 用法 基本 装饰
2023-09-27 14:27:09 时间
简介
装饰器(Decorator)是一种与类(class)相关的语法,用来注释或修改类和类方法。
-
特点
-
- 编译时执行
例1
@testable
class MyTestableClass {
// ...
}
function testable(target) {
target.isTestable = true;
}
MyTestableClass.isTestable // true
这里的 @testable
就是一个装饰器。它修改了 MyTestableClass
这个类的行为,为它加上了静态属性 isTestable
。testable
函数的参数 target
是 MyTestableClass
类本身。
例2
装饰器外面再封装一层函数。
function testable(isTestable) {
return function(target) {
target.isTestable = isTestable;
}
}
@testable(true)
class MyTestableClass {}
MyTestableClass.isTestable // true
@testable(false)
class MyClass {}
MyClass.isTestable // false
例3(改写react)
// before
class MyReactComponent extends React.Component {}
export default connect(mapStateToProps, mapDispatchToProps)(MyReactComponent);
// now
@connect(mapStateToProps, mapDispatchToProps)
export default class MyReactComponent extends React.Component {}
例4(方法的装饰)
class Person {
@readonly
name() { return `${this.first} ${this.last}` }
}
function readonly(target, name, descriptor){
// descriptor对象原来的值如下
// {
// value: specifiedFunction,
// enumerable: false,
// configurable: true,
// writable: true
// };
descriptor.writable = false;
return descriptor;
}
readonly(Person.prototype, 'name', descriptor);
// 类似于
Object.defineProperty(Person.prototype, 'name', descriptor);
装饰器第一个参数是类的原型对象,上例是Person.prototype,装饰器的本意是要“装饰”类的实例,但是这个时候实例还没生成,所以只能去装饰原型(这不同于类的装饰,那种情况时target参数指的是类本身);第二个参数是所要装饰的属性名,第三个参数是该属性的描述对象。
相关文章
- [转] JS中的call()方法和apply()方法用法总结
- js中call与apply用法
- js - 正斜杆网址转换
- window.open()的用法,js打开新窗体
- JS模块化
- Web前端-Vue.js必备框架(四)
- js 数组 map() 基本用法--需求:1.处理数组对象----2.处理对象中包含多个对象-返回一个数组对象
- js 获取字符串中最后一个斜杠后面的内容
- JS操作css样式用法
- Idea-每次修改JS文件都需要重启Idea才能生效解决方法
- [js高手之路]深入浅出webpack教程系列9-打包图片(file-loader)用法
- 字符串js编码转换成实体html编码的方法(防范XSS攻击)
- js中window.location.search的用法和作用。以及自定义存储和读取localStorage的API(重要)
- JavaScript是如何工作的: CSS 和 JS 动画底层原理及如何优化它们的性能
- Element-UI+Vue.js
- JS forEach()与map() 用法(转载)
- js获取页面url