简体   繁体   English

动态继承TypeScript

[英]Dynamical inheritance TypeScript

JavaScript permit dynamical inheritance. JavaScript允许动态继承。 I was wondering if TypeScript take it into account. 我想知道TypeScript是否考虑到它。 The following code might illustrate the problem. 以下代码可能说明了此问题。

// 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"

As you can see we add an object f1, which is an instance of fn1, in the prototype chain of f2. 如您所见,我们在f2的原型链中添加了一个对象f1,它是fn1的一个实例。 My question is therefore the following: can we reproduce this behave in TypeScript by using classes? 因此,我的问题是:我们可以使用类在TypeScript中重现此行为吗? How would I change the following code to have the expected output? 如何更改以下代码以达到预期的输出?

// 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")

I think what you are looking for is like an intersection mixing. 我认为您正在寻找的就像是路口混合。 There's a simple example found at the typescript docs . typescript docs上有一个简单的示例。 To do what you want, you, you can basically just assign the mixing's resulting class to the to inheriting class, then copy all properties of the class you want to be the extending to the result: 要执行您想做的事情,您基本上可以将混合的结果类分配给继承类,然后将要扩展的类的所有属性复制到结果:

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