NodeJs Decorator装饰器

本文探讨了JavaScript中的装饰器(Decorator)概念,它用于修改类的行为。通过示例展示了`apply`的作用,如何使一个类继承另一个类的方法和属性。此外,文章还提及了`Route`装饰器在实际场景中的应用。
摘要由CSDN通过智能技术生成

装饰器的作用

装饰器(Decorator)是一个函数,用来修改类的行为。这是ES7的一个提案,目前Babel转码器已经支持。

console.log('start decorate.js');
//对类的装饰 为类添加一个静态属性
@addCountry
class tank_1 {
  // ...
}
//
function addCountry(target) {
  target.country = "Chinese";
}

console.log(tank_1.country);

//对类的实例装饰 添加实例属性 通过目标类的prototype对象操作

@addLevel
class tank_2 {

}

function addLevel(target){
  target.prototype.Level=10;
}
console.log(new tank_2().Level)


//如果觉得一个参数不够用,可以在修饰器外面再封装一层函数。
@addTankType("轻坦")
class tank_3{

}
function addTankType(tankType){
return function(target){
  target.tankType=tankType
}
}
console.log(tank_3.tankType);

//对类中的方法的修饰
/*
修饰器函数readonly一共可以接受三个参数。

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参数指的是类本身);第二个参数是所要修饰的属性名,第三个参数是该属性的描述对象。
*/
class tank_4{

  @shoot
  shoot(a,b){
    console.log("shoot"+a+" "+b)
  }
}

function shoot(target,name,descriptor){
  //descriptor.value:表示tank_4对象的方法shoot(a,b)
  var oldValue = descriptor.value;

  console.log(descriptor.value);
  descriptor.value = function() {
    console.log(`Calling ${name} with`, arguments);
    return oldValue.apply(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值