[英]I want to create an extension method to all object or reference that are created using TypeScript
Actually, I am currently thinking of creating an extension method to all the object or reference that are created in my component 实际上,我目前正在考虑为在组件中创建的所有对象或引用创建扩展方法。
I know how to create an extension method in typeScript but I am not able to get what I want to use an interface to get the behavior I wanted. 我知道如何在typeScript中创建扩展方法,但是我无法获得要使用接口来获得想要的行为的东西。
I tried using the Object in the interface but it won't work 我尝试在界面中使用对象,但无法正常工作
MyExtension Method : extension.model.ts MyExtension方法:extension.model.ts
declare global {
interface Object {
thousandsSeperator(): String;
}
}
Object.prototype.thousandsSeperator = function(): string {
return Number(this).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
export {};
// this is just a simple extension method
Now, whenever if someone tries to create an object of class or reference of an interface then, they should get the extension method I created. 现在,只要有人尝试创建类的对象或接口的引用,他们就应该获得我创建的扩展方法。
// Object
Object1 = new MyComponentClass();
// Reference
Object2: MyComponentClass;
this.Object1.thousandsSeperator();
this.Object2.thousandsSeperator();
fooObj in the below example is assigned to Foo object.
下例中的fooObj分配给Foo对象。 so all the methods in the object and the inherited properties can be accessed.
因此可以访问对象中的所有方法和继承的属性。
But 但
fooObj1 is just declared as Foo type.
fooObj1只是声明为Foo类型。 ie, we are declaring that the fooObj1 can only have Object of Foo type.
即,我们声明fooObj1只能具有Foo类型的Object。
// Add thousandsSeperator in the Object interface.
interface Object {
thousandsSeperator(): String;
}
// assign the method to the object prototype.
Object.prototype.thousandsSeperator = function(): string {
// this is the instance of the object and value is the property on it.
return Number(this.value).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};
// now all the object of the created will get the thousandsSeperator method.
class Foo {
value: string = '123456';
}
// create an object
let fooObj: Foo = new Foo();
// here on the fooObj thousandsSeperator method can be accessed.
fooObj.thousandsSeperator();
// undeclared variable.
let fooObj1: Foo
// this is eqivalent to var fooObj1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.