简体   繁体   English

在使用“this”关键字的方法中,如何从其他属性访问对象属性?

[英]How do I access the object properties from other properties, while within a method using the 'this' keyword?

 const america = { name: 'United State of America', yearFounded: 1776, details: { symbol: 'eagle', currency: 'USD', printDetails: function() { console.log(`The ${this.name} was founded in ${this.yearFounded} and its currency is ${this.currency}, with an ${this.symbol} symbol`); } } } america.details.printDetails();

The name and the founding year are not part of the object on which you are calling the method, but some other object.名称和创建年份不是调用方法的对象的一部分,而是其他对象的一部分。 You can access it by explicitly referring to america.… , there is no way to access it through the this keyword .您可以通过显式引用america.…来访问它america.… ,无法通过this关键字访问它。 The this value in your method call refers to the details object only.方法调用中的this值仅指details对象。

Alternatively, move the printDetails method to the outer object (so that you can call america.printDetails() instead of america.details.print() ), and use this.name and this.details.currency respectively.或者,将printDetails方法移动到外部对象(以便您可以调用america.printDetails()而不是america.details.print() ),并分别使用this.namethis.details.currency Or just flatten the entire structure into a single object.或者只是将整个结构展平成一个单一的对象。

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

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