[英]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();
名称和创建年份不是调用方法的对象的一部分,而是其他对象的一部分。 您可以通过显式引用america.…
来访问它america.…
,无法通过this
关键字访问它。 方法调用中的this
值仅指details
对象。
或者,将printDetails
方法移动到外部对象(以便您可以调用america.printDetails()
而不是america.details.print()
),并分别使用this.name
和this.details.currency
。 或者只是将整个结构展平成一个单一的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.