Skip to content Skip to sidebar Skip to footer

Deeply Self Reference An Object's Properties

Is it possible to deeply self reference within a JS object? I know it is possible to self reference at the same level, like so: I'm just curious if it would be possible to do so f

Solution 1:

One solution is to call your cb method with foo object as a context then this will refer to foo and a and b will be found, but then you should use regular function instead of arrow function.

var foo = {
  a: 'bar',
  b: 'baz',
  c: {
    ca: 'hello',
    cb: function() {
      returnthis.a + this.b;
    }
  }
};

console.log(foo.c.cb.call(foo));

Another solution is to turn c into getter and then you can use arrow functions as context will be context of the getter which is root object in this case.

var foo = {
  a: 'bar',
  b: 'baz',
  getc() {
    return {
      ca: 'hello',
      cb: () => {
        returnthis.a + this.b;
      }
    }
  }
};

console.log(foo.c.cb());

Solution 2:

You would have to create a function that returns a referenced "self".

You can apply the new properties to this by referencing the scope at the top level.

let foo = createFoo();
let bar = Object.assign(createFoo(), {
  a : 'zam',
  b : 'zip'
});

console.log(foo.c.cb()); // barbazconsole.log(bar.c.cb()); // zamzip (extended foo)functioncreateFoo() {
  let self = {}; // Create a new scope.returnObject.assign(self, {
    a: 'bar',
    b: 'baz',
    c: {
      ca: 'hello',
      cb: () => self.a + self.b
    }
  });
}

Post a Comment for "Deeply Self Reference An Object's Properties"