闽公网安备 35020302035485号
function myDecorator(target) {
// 给目标对象加个标记,表示它被装饰过了
target.decorated = true;
}
这个示例中的myDecorator是一个简单的装饰器函数,它给目标添加了一个decorated属性,表示这个对象被装饰过了。数据验证:在设置属性值时进行数据校验。
function addTimestamp(target) {
// 给类的原型添加一个timestamp属性,初始化为当前时间
target.prototype.timestamp = new Date();
}
@addTimestamp
class MyClass {}
const instance = new MyClass(); // 堆代码 duidaima.com
console.log(instance.timestamp); // 输出当前日期和时间
在这个示例中,addTimestamp装饰器为MyClass类添加了一个timestamp属性。当创建MyClass的实例时,该属性会被初始化为当前的日期和时间。function logMethod(target, propertyKey, descriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args) {
console.log(`调用方法${propertyKey},参数为:`, args);
return originalMethod.apply(this, args);
};
return descriptor;
}
class MyClass {
@logMethod
greet(name) {
return `Hello, ${name}!`;
}
}
const instance = new MyClass();
console.log(instance.greet('World'));
// 输出:
// 调用方法greet,参数为: [ 'World' ]
// Hello, World!
在这个示例中,logMethod装饰器记录了方法调用时的参数,然后再调用原始方法。function capitalize(target, propertyKey, descriptor) {
const originalGetter = descriptor.get;
descriptor.get = function () {
const result = originalGetter.call(this);
return result.toUpperCase();
};
return descriptor;
}
class Person {
constructor(name) {
this._name = name;
}
@capitalize
get name() {
return this._name;
}
}
const person = new Person('john');
console.log(person.name); // 输出: JOHN
在这个示例中,capitalize装饰器修改了name属性的getter,使其返回大写的名字。function readOnly(target, propertyKey) {
Object.defineProperty(target, propertyKey, {
writable: false
});
}
class Car {
@readOnly
make = 'Toyota';
}
const myCar = new Car();
console.log(myCar.make); // 输出: Toyota
myCar.make = 'Honda'; // 此操作将静默失败或在严格模式下抛出错误
console.log(myCar.make); // 仍输出: Toyota
在这个示例中,readOnly装饰器使make属性变为只读,因此任何修改该属性值的尝试都不会成功。function logParameter(target, propertyKey, parameterIndex) {
const originalMethod = target[propertyKey];
target[propertyKey] = function (...args) {
console.log(`方法${propertyKey}的第${parameterIndex}个参数值为:`, args[parameterIndex]);
return originalMethod.apply(this, args);
};
}
class User {
greet(@logParameter name) {
return `Hello, ${name}!`;
}
}
const user = new User();
console.log(user.greet('Alice'));
// 输出:
// 方法greet的第0个参数值为: Alice
// Hello, Alice!
在这个示例中,logParameter装饰器记录了特定参数的值,每当调用该方法时都会执行此记录。