[英]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.name
和this.details.currency
。 Or just flatten the entire structure into a single object.或者只是将整个结构展平成一个单一的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.