装饰器的作用
装饰器(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(