Reputation: 41
How can I get reference to the constructor function for any object in typescript?
Example in JavaScript:
var anyObject = new this.constructor(options);
or
var anyObject = new someObj.constructor(options);
or
class Greeter {
greeting: string;
constructor(message: string, options: any) {
this.options = options;
this.greeting = message;
} greet() {
return "Hello, " + this.greeting;
} createAnyObj(){
return new this.constructor(this.options);
}
}
var t= new Greeter('mes',{param1: 'val1'});
var b=t.createAnyObj();
Thanks.
More examples:
>>>Link to typescript playground
Upvotes: 1
Views: 506
Reputation: 41
This problem was solved with next solution:
module Example{
// Thank you, JavaScript!
export function getConstructor(obj){
return obj.constructor;
}
export class A{
constructor(private options: any){}
dublicate(){
return new (getConstructor(this))(this.options);
}
someMethod(){
return 'This is class A';
}
}
export class B extends A{
someMethod(){
return 'This is class B';
}
}
}
// Class A
var objA = new Example.A({key1: 'val1'});
console.log(objA.someMethod(), objA); //=> This is class A
var objA2 = objA.dublicate();
console.log(objA2.someMethod(), objA2); //=> This is class A
// Class B
var objB = new Example.B({key2: 'val2'});
console.log(objB.someMethod(), objB); //=> This is class B
var objB2 = objB.dublicate();
console.log(objB2.someMethod(), objB2); //=> This is class B
Live example => Open playground
Upvotes: 1
Reputation: 251082
You could achieve what you need using the following code:
class A {
constructor(public options: any) {
}
duplicate() {
return new A(this.options);
}
someMethod() {
return 'Hello! I am class A!';
}
}
class B extends A {
constructor(options: any) {
super(options);
}
someMethod() {
return 'This is class B!';
}
duplicate() : A {
return new B(this.options);
}
}
var objA = new A({key1: 'value1'});
var objWhithOptionsObjA = objA.duplicate(); //=> Instaceof class A
alert(objWhithOptionsObjA.someMethod());
var objB = new B({key2: 'value2'});
var objWhithOptionsObjB = objB.duplicate(); //=> Instaceof class B
alert(objWhithOptionsObjB.someMethod());
You need a constructor on B
that just passes options to the super class. You override the duplicate method to return a B
, which is a sub-type of A
.
Upvotes: 2
Reputation: 4495
Use the new
operator to instantiate the object with the required parameter in the constructor. This is similar to how you do it in other Object Oriented programming languages, below is an example from the typescript official website
class Greeter {
constructor(public message: string, public options?: any) {
}
greet() {
return "Hello, " + this.message;
}
createAnyObj(){
return new Greeter(this.message, this.options);
}
}
var greeter = new Greeter("world");
Upvotes: 0