How to pass default value to object by reference?

0 like 0 dislike
7 views
Need the ability to add objects to the list with the default value equal for all. This value can be changed, and it is expected that this will change all the object properties specified list(referencing this value) when you add. It will be possible to directly modify an object property with a default value to another, then change the default value to change a property for all objects except this one.

Sketched this code, but it does not work as expected.

function Some() { this.name = 'Some'; } function Other() { this.name = 'Other'; } function Filters() { this.handler = new Some(); this.list = { }; this.add = function (name, filter) { this.list[name] = Object.create({ handler: this.handler }); } } let attempt = new Filters(); attempt.add('first'); attempt.handler = new Other(); document.writeln(attempt.handler.name); document.writeln(attempt.list['first'].handler.name);


In the end, the value prop of the list objects will not change, although it was expected that both values will be other.
by | 7 views

1 Answer

0 like 0 dislike
You can write something using prototypes:

class Filters { constructor(x) { this.default = { prop: 'foo' }; this.list = {}; } add(name) { this.list[name] = Object.create(this.default); } } let attempt = new Filters(); attempt.add('first'); attempt.add('second'); attempt.list['second'].prop = 'custom'; console.log(attempt.list['first'].prop attempt.list['second'].prop); // → foo custom attempt.default.prop = 'bar'; console.log(attempt.list['first'].prop attempt.list['second'].prop); // → bar custom


Or parasuicide with the Object.defineProperty
class Filters { constructor(x) { this.prop = 'foo'; this.list = {}; } add(name) { const item = this.list[name] = Object.defineProperty({}, 'prop', { enumerable: true, configurable: true, get: () => this.prop, set: (v) => { Object.defineProperty(item, 'prop', { enumerable: true, writable: true, value: v }); } }); } } let attempt = new Filters(); attempt.add('first'); attempt.add('second'); attempt.list['second'].prop = 'custom'; console.log(attempt.list['first'].prop attempt.list['second'].prop); // → foo custom attempt.prop = 'bar'; console.log(attempt.list['first'].prop attempt.list['second'].prop); // → bar custom
by

Related questions

0 like 0 dislike
2 answers
asked May 12, 2019 by Nikita07
0 like 0 dislike
1 answer
0 like 0 dislike
1 answer
0 like 0 dislike
2 answers
110,608 questions
257,186 answers
0 comments
28,742 users