Deeply self reference an object's properties

妖精的绣舞 提交于 2020-01-24 13:22:29

问题


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:

var foo = {
  a: 'bar',
  b: 'baz',
  c: () => {
    return this.a + this.b;
  }
};
console.log(foo.c()); // barbaz

I'm just curious if it would be possible to do so from deeper down...

var foo = {
  a: 'bar',
  b: 'baz',
  c: {
    ca: 'hello',
    cb: () => {
          return this.a + this.b;
        }
    }
};
console.log(foo.c.cb()); // barbaz

If not... How would one go about getting this to work?


回答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() {
      return this.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',
  get c() {
    return {
      ca: 'hello',
      cb: () => {
        return this.a + this.b;
      }
    }
  }
};

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



回答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()); // barbaz
console.log(bar.c.cb()); // zamzip (extended foo)

function createFoo() {
  let self = {}; // Create a new scope.
  return Object.assign(self, {
    a: 'bar',
    b: 'baz',
    c: {
      ca: 'hello',
      cb: () => self.a + self.b
    }
  });
}


来源:https://stackoverflow.com/questions/59412087/deeply-self-reference-an-objects-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!