繁体   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();

名称和创建年份不是调用方法的对象的一部分,而是其他对象的一部分。 您可以通过显式引用america.…来访问它america.… ,无法通过this关键字访问它。 方法调用中的this值仅指details对象。

或者,将printDetails方法移动到外部对象(以便您可以调用america.printDetails()而不是america.details.print() ),并分别使用this.namethis.details.currency 或者只是将整个结构展平成一个单一的对象。

暂无
暂无

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

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