1

如何获取 typescript 中任何对象的构造函数的引用?

JavaScript 中的示例:

var anyObject = new this.constructor(options);

或者

var anyObject = new someObj.constructor(options);

或者

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();

谢谢。

更多示例:

>>>链接到打字稿游乐场

4

3 回答 3

2

您可以使用以下代码实现所需的功能:

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());

您需要一个构造函数,B它只是将选项传递给超类。您覆盖重复方法以返回 a B,它是 的子类型A

于 2013-02-12T10:27:55.737 回答
1

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

于 2013-02-14T05:17:20.197 回答
0

使用new运算符在构造函数中使用所需参数实例化对象。这类似于您在其他面向对象编程语言中的操作方式,下面是 typescript 官方网站的示例

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");
于 2013-02-12T06:50:20.063 回答