在JavaScript中 使用getter,我们可以通过其他方式将属性作为属性进行访问。关键字“ get ”用于完成此过程。让我们简要地讨论一下。
在下面的示例中,属性' details '用作函数' details() '。因此,我们不会获得任何结果。相反,如果我们删除括号,关键字' get '确保将属性“ details”视为属性而不是函数。
<html> <body> <p id = "prop"></p> <script> var business = { product: "Tutorix", parent : "Nhooo", get details() { return this.product+" is the product of" + " " + this.parent; } }; document.getElementById("prop").innerHTML = business.details(); </script> </body> </html>
在这里,由于括号中的 括号已删除,因此' get '关键字可确保将属性 “ details”视为属性 而不是函数。
<html> <body> <p id = "prop"></p> <script> var business = { product: "Tutorix", parent : "Nhooo", get details() { return this.product+" is the product of" + " " + this.parent; } }; document.getElementById("prop").innerHTML = business.details; </script> </body> </html>
输出结果
Tutorix is the product of Nhooo