简体   繁体   English

深度自引用对象的属性

[英]Deeply self reference an object's properties

Is it possible to deeply self reference within a JS object?是否可以在 JS 对象中进行深度自引用?

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?如果没有......人们将如何让它发挥作用?

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.一种解决方案是使用 foo 对象作为上下文call cb方法,然后this将引用foo并找到ab ,但是您应该使用常规函数而不是箭头函数。

 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.另一种解决方案是将c转换为 getter,然后您可以使用箭头函数,因为上下文将是 getter 的上下文,在这种情况下是根对象。

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

You would have to create a function that returns a referenced " self ".您必须创建一个返回引用的“ self ”的函数。

You can apply the new properties to this by referencing the scope at the top level.您可以通过在顶层引用范围来将新属性应用于this

 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 } }); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM