繁体   English   中英

动态继承TypeScript

[英]Dynamical inheritance TypeScript

JavaScript允许动态继承。 我想知道TypeScript是否考虑到它。 以下代码可能说明了此问题。

// inheritance.js
function fn1() {
  this.a = "fn1";
}

function fn2() {
  // ...
}

let f1 = new fn1(); // "instance" of fn1
let f2 = new fn2(); // "instance" of fn2

// inheritance
f2.__proto__ = f1;

// f2.a inherits from f1
console.log(f2.a); // output: "fn1"

如您所见,我们在f2的原型链中添加了一个对象f1,它是fn1的一个实例。 因此,我的问题是:我们可以使用类在TypeScript中重现此行为吗? 如何更改以下代码以达到预期的输出?

// inheritance.ts
class class1 {
  public a: string = "class1";
}

class class2 extends class1 {
  // ...
}

let c1 = new class1();
let c2 = new class2();

console.log(c1.a); // output: "class1"

// this line would not work
c2.__proto__ = c1;

// change value c1.a
c1.a = "dynamical inheritance test";

console.log(c2.a); // should print value of c1.a (i.e "dynamical inheritance test")

我认为您正在寻找的就像是路口混合。 typescript docs上有一个简单的示例。 要执行您想做的事情,您基本上可以将混合的结果类分配给继承类,然后将要扩展的类的所有属性复制到结果:

function extendDynamic<T, U>(first: T, second: U): T & U {
    let result = <T & U>{};
    (<any>result) = (<any>first);
    for (let it in second) {
        if (second.hasOwnProperty(it)) {
            (<any>result)[it] = (<any>second[it]);
        }
    }
    return result;
}

class Class1 {
    public a: string;
    constructor(n: string) {
        this.a = n;
    }
}

class Class2 {
    b: string = 'bbb';
}

const a = new Class1("bar");
const b = extendDynamic(a, new Class2());
a.a = 'foo';
console.log(b.a, b.b); // foo, bbb

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM