javascript - 动态地将属性绑定到类
问题描述
我想动态创建一个打字稿类并动态添加一个属性给它。
该属性可能是函数或 Promise 或任何其他类型和用途this
,我希望this
在其中引用该类。
let MyClass = class{
public property: any;
public ok = 1;
}
let property = function(){ console.log(this.ok); }
// now we want `this` to refer to MyClass instead of its function
// first trial
MyClass.prototype.property= property;
// second trial: using bind()
// we have another problem here, property not always a fnction
let propertyBind = property.bind(MyClass)
// third trial: add property while creating the class
let MyClass = class{
public property = property ;
public ok =1;
}
ifproperty
是一个函数,我们不能将this
其作为参数传递给它,因为创建的类将提供给第三方,该第三方在没有任何参数的情况下强制执行签名
let property = (this)=>{ console.log(this.ok); }
``
解决方案
class BaseClass {
public property: unknown;
public ok = 1;
}
function addProperty<Base extends new (...args: any) => any, T>(
baseClass: Base,
property: T extends Function ? (this: InstanceType<Base>) => void : T
) {
return class extends baseClass {
public property = property;
};
}
const MyClass1 = addProperty(BaseClass, "hello");
const myClass1 = new MyClass1();
console.log(myClass1.property); // "hello"
const MyClass2 = addProperty(BaseClass, function () {
// here `this` has type BaseClass
this.ok++;
});
const myClass2 = new MyClass2();
myClass2.property();
console.log(myClass2.ok); // 2
推荐阅读
- sql - SQL Server 中的 FROM 子句
- java - FileOutput Stream 删除文本文件内容
- terminal - xtermjs,关于使用的几个问题
- javascript - 时间复杂度是根据程序在单个输入上工作的时间来计算的
- python - 对列应用过滤以保留具有特定结构的值
- javascript - React App 中的重复 setInterval 事件
- unreal-engine4 - 有没有办法在 Ue4 中手动调用重叠事件?
- powershell - 我正在尝试使用 Powershell 在 AD 中创建测试帐户/新 ADUser 帐户。收到错误:找不到目录对象
- apache-flink - 使用 AllowNonRestoredState 将 TTL 添加到现有状态并保留快照中的其余状态
- php - 为什么我收到未捕获的错误:调用未定义的函数 get_header()?