Javascript中方法对同级属性的引用

Javascript中方法对同级属性的引用,javascript,Javascript,如何从Javascript中的方法访问同级属性?想做这件事似乎很简单,但我还没有找到办法。具体来说,考虑下面的代码。 设f={ a:3, printMyBrother{console.logX} }我的兄弟 F 要以编程方式在控制台上记录3,我必须将上述代码中的X更改为什么?如果您稍微更改一下代码,就可以这样做: 这是一个不同的工作方式的例子。它以这种方式工作的原因是javascript的this的有趣规则 设f={ a:3, 打印我的兄弟信息{ console.logmessage,this

如何从Javascript中的方法访问同级属性?想做这件事似乎很简单,但我还没有找到办法。具体来说,考虑下面的代码。

设f={ a:3, printMyBrother{console.logX} }我的兄弟 F
要以编程方式在控制台上记录3,我必须将上述代码中的X更改为什么?

如果您稍微更改一下代码,就可以这样做:

这是一个不同的工作方式的例子。它以这种方式工作的原因是javascript的this的有趣规则

设f={ a:3, 打印我的兄弟信息{ console.logmessage,this.a } } 让printMyBrother=f.printMyBrother; 控制台。组“功能”; console.log'function'; f、 printMyBrother“函数调用” //我哥哥不受约束是不会独自工作的 printMyBrother“未绑定函数调用”; //绑定printMyBrother变量以始终引用f printMyBrother=printMyBrother.bindf; printMyBrother“绑定函数调用” console.groupEnd; F类{ a=3; //默认情况下,这与类没有绑定 //因为它不是一个箭头函数 //但是,您可以在构造函数中手动绑定它 PrintMyBrotherRunBoundMessage{ console.log'classF',message,this.a }; //默认情况下,这将绑定到类 //因为这是一个箭头函数 //这应该适用于除IE之外的所有主要浏览器 printMyBrotherBound=消息=>{ console.log'classF',message,this.a } } 设classF=新classF; console.group'Class方法' console.log'Class方法' printMyBrother=classF.printmybrotherrunbound; classF.PrintMyBrother“在课堂上”运行绑定; 试一试{ 打印我的兄弟“未绑定”; }捕捉错误{ log'unbound类函数出错,因为这是未定义的'; } 控制台.groupEnd 控制台。组“类箭头函数”; 日志“类箭头函数”; printMyBrother=classF.printMyBrotherBound; printMyBrotherBound“箭头函数”; printMyBrother‘未绑定箭头函数’;
console.groupEnd;将您的对象存储在另一个变量中,例如o和引用o.aThat尚未回答此问题。鉴于上面的文字代码,您想要的是不可能的。如果f是你的对象,你调用了f.printMyBrother,你可以使用这个.a,但是因为你直接引用了printMyBrother函数,原始对象的所有上下文都是lost,这对我来说很奇怪,这是不可能的。许多语言都有一个self关键字来引用包含对象。在这些语言中,我们可以用X->self.a代替。即使在HTML中,我们也可以通过使用parentElement属性来实现这一点。我不明白为什么我们不能在Javascript中实现这一点。对于这个问题,你不会得到一个好的答案。你可以试着问克罗克福德,但他可能不会回答。同时,这些可能有助于,我知道你指出的事情。这就是为什么我用我的方式表达我的问题。