簡體   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