-
Creator 版本:3.8.x
-
目标平台: Chrome & Android
TS规范里面的属性装饰器用得挺多的,结果cocos里面不支持吗?在ccclass里面不支持也就算了,非ccclass里面也不行,很难受,有什么解决方案吗?
原本有一些属性装饰器,比如【1】get时从localstorage中获取,set时更新,【2】添加set日志,观察数据,…
以下是 AI 生成的一段代码,在 https://www.typescriptlang.org/play 在线执行很好,在cocos里面就废了。
`function LogProperty(target: any, propertyName: string | symbol) {
// 检查目标是否是原型(实例属性)还是构造函数(静态属性)
const isStatic = typeof target === ‘function’;
const actualTarget = isStatic ? target.prototype : target;
let value: any;
const getter = function() {
console.log(`Getting ${String(propertyName)}: ${value}`);
return value;
};
const setter = function(newVal: any) {
console.log(`Setting ${String(propertyName)}: ${newVal}`);
value = newVal;
};
Object.defineProperty(actualTarget, propertyName, {
get: getter,
set: setter,
enumerable: true,
configurable: true
});
}
function LogStaticProperty(target: any, propertyName: string | symbol) {
// 静态属性直接装饰在构造函数上
let value: any;
const getter = function() {
console.log(`Getting static ${String(propertyName)}: ${value}`);
return value;
};
const setter = function(newVal: any) {
console.log(`Setting static ${String(propertyName)}: ${newVal}`);
value = newVal;
};
Object.defineProperty(target, propertyName, {
get: getter,
set: setter,
enumerable: true,
configurable: true
});
}
class MyClass {
@LogProperty
instanceProperty: string = ‘’;
@LogStaticProperty
static staticProperty: string;
show() {
this.instanceProperty = '3323';
}
}
const a = new MyClass();
a.instanceProperty = ‘123’;
MyClass.staticProperty = ‘r33’;
a.show();`






