简体   繁体   中英

Dynamical inheritance TypeScript

JavaScript permit dynamical inheritance. I was wondering if TypeScript take it into account. 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. My question is therefore the following: can we reproduce this behave in TypeScript by using classes? 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 . 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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