2

I need to add new objects to the list (Filters.list)
* Filters.prop - is a default prop
* list items also have prop - list[name].prop (equal default prop)

Chage default Filters.prop -> [not] change item list[name].prop
Where is the mistake?

function Filters() {
  this.prop = 'some';  
  this.list = { };
  
  this.add = function (name) {
    this.list[name] = {
      prop: this.prop,
    };
  }
} 
 
let attempt = new Filters();
attempt.add('first');
attempt.prop = 'other';

document.writeln(attempt.prop);
document.writeln(attempt.list['first'].prop);

After run snippet output: other some
But I need: other other

I thought the property would be saved by reference. But this is not so, it does not change. When I change Filters.prop I expected that too it will change list[name].prop

3

1 Answer 1

2

The problem with this is that, as you noticed yourself, the value is passed the way you're doing it instead of the reference.

Thanks to JavaScript get, you can return the value of prop of the surrounding object within a function which behaves like an attribute.

function Filters() {
  this.prop = 'some';  
  this.list = { };
  
  this.add = function(name) {
    let self = this;
    this.list[name] = {
      get prop() {
        return self.prop;
      },
    };
  }
}

let attempt = new Filters();
attempt.add('first');
attempt.prop = 'other';

document.writeln(attempt.prop)
document.writeln(attempt.list['first'].prop)

Side note: I use the variable self here because using this.prop within get prop() would reference the wrong object and hence cause a recursion.

Not the answer you're looking for? Browse other questions tagged or ask your own question.