実際、私は現在、コンポーネントで作成されたすべてのオブジェクトまたは参照への拡張メソッドを作成することを考えています。
typeScriptで拡張メソッドを作成する方法は知っていますが、インターフェイスを使用して必要な動作を取得するために必要なものを取得できません。
インターフェイスでオブジェクトを使用しようとしましたが、機能しません
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
これで、誰かがクラスのオブジェクトまたはインターフェイスの参照を作成しようとすると、私が作成した拡張メソッドを取得する必要があります。
// Object
Object1 = new MyComponentClass();
// Reference
Object2: MyComponentClass;
this.Object1.thousandsSeperator();
this.Object2.thousandsSeperator();
以下の例のfooObjは、Fooオブジェクトに割り当てられています。そのため、オブジェクト内のすべてのメソッドと継承されたプロパティにアクセスできます。
だが
fooObj1はFooタイプとして宣言されています。つまり、fooObj1はFooタイプのオブジェクトのみを持つことができると宣言しています。
// 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;
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加