Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

Calling constructor on an object created via Object.create() in TypeScript

I want to use Object.create(prototype) to create an object that inherits the values of another object. However, the prototype object is an ES6 object that has a class and a constructor. I want to be able to call the constructor on the newly-created object; however it appears that no matter how I do it, the constructor returns a new object instead of modifying the existing object.

So for example:

class Foo {
  constructor(public readonly name: string) {}
}
const parent = new Foo('test');
const child = Object.create(parent);
parent.constructor.call(child, 'other');

expect(child.name).toBe('other'); // FAIL - name is 'test'

I realize what I am trying to do may seem odd, so here's some context - these objects are being deserialized from a JSON file, where the serialized data allows for prototype inheritance - i.e. one JSON object can inherit the properties of another; moreover, they can also be re-serialized back into JSON preserving this relationship, which means that I don't want to simply Object.assign() all of the properties of the parent into the child (since now the child would have a copy of all the parent's properties instead of dynamically inheriting them.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...