本文共 3921 字,大约阅读时间需要 13 分钟。
var myObj = { myPropOne: 1, myPropTwo: 2};// modify property descriptorObject.defineProperty( myObj, 'myPropOne', { writable: false, // 是否允许该属性值更改 enumerable: false, // 是否允许key被枚举,话句话说for in 或者Object.keys() 不会输出key configurable: false// 目标属性是否可以被删除或是否可以再次修改特性} );复制代码
class User { constructor( firstname, lastName ) { this.firstname = firstname; this.lastName = lastName; } @readonly getFullName() { return this.firstname + ' ' + this.lastName; }}// create instancelet user = new User( 'John', 'Doe' );console.log( user.getFullName() );// 某天我不小心重写了这个方法User.prototype.getFullName = function() { return 'HACKED!';}// 输出 HACKED! 与预期不符,怎么避免此类情况发生// 方法1 这是最好的解决方案么?修饰器登场Object.defineProperty( User.prototype, 'getFullName', { writable: false});// 将此方法添加到修饰方法getFullName上function readonly( target, property, descriptor ) { descriptor.writable = false; return descriptor;}复制代码
function log( logMessage ) { // return decorator function return function ( target, property, descriptor ) { // save original value, which is method (function) let originalMethod = descriptor.value; // replace method implementation descriptor.value = function( ...args ) { console.log( '[LOG]', logMessage ); // here, call original method // `this` points to the instance return originalMethod.call( this, ...args ); }; return descriptor; }}class User { constructor( firstname, lastName ) { this.firstname = firstname; this.lastName = lastName; } @log('calling getFullName method on User class') getFullName() { return this.firstname + ' ' + this.lastName; }}var user = new User( 'John', 'Doe' );console.log( user.getFullName() );复制代码
// 解释:descriptor.initializer函数由Babel内部使用来创建对象属性的属性描述符的值function toCase( CASE = 'lower' ) { return function ( target, name, descriptor ) { let initValue = descriptor.initializer(); descriptor.initializer = function(){ return ( CASE == 'lower' ) ? initValue.toLowerCase() : initValue.toUpperCase(); } return descriptor; }}class User { @toCase( 'upper' ) firstName = 'default_first_name'; lastName = 'default_last_name'; constructor( firstName, lastName ) { if( firstName ) this.firstName = firstName; if( lastName ) this.lastName = lastName; } getFullName() { return this.firstName + ' ' + this.lastName; }}console.log( new User() );复制代码
function withLoginStatus( UserRef ) { return class extends UserRef { constructor( ...args ) { super( ...args ); this.isLoggedIn = false; } setLoggedIn() { this.isLoggedIn = true; } }}@withLoginStatusclass User { constructor( firstName, lastName ) { this.firstName = firstName; this.lastName = lastName; }}let user = new User( 'John', 'Doe' );console.log( 'Before ===> ', user );// set logged inuser.setLoggedIn();console.log( 'After ===> ', user );复制代码
1、创建项目文件2、命令行进入该项目目录 npm init 3、npm install babel-core babel-plugin-transform-decorators4、安装 npm install babel-plugin-transform-decorators-legacy --save-dev5、.babelrc添加{ "plugins": [ "transform-decorators-legacy" ]}复制代码
原文发布时间为:2018年06月28日
原文作者:chen小白
本文来源: 如需转载请联系原作者