JavaScript 对象访问器
访问对象时用到 getter 和 setter 关键字。当访问某个属性时,getter 返回值;setter 则接收一个参数并用该参数设置对象内部的属性值。
以下是 JavaScript 中访问对象的代码:-
示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .sample { font-size: 18px; font-weight: 500; color: red; } </style> </head> <body> <h1>JavaScript Object Accessors</h1> Enter a number <input class="num" type="number" /> <div class="sample"></div> <button class="Btn">CLICK HERE</button> <h3> Click on the above button to set the age value and display it </h3> <script> let sampleEle = document.querySelector(".sample"); let testObj = { age: "", set AGE(val) { this.age = val; }, get AGE() { return this.age; }, }; document.querySelector(".Btn").addEventListener("click", () => { let number = document.querySelector(".num").value; testObj.AGE = number; sampleEle.innerHTML = "AGE = " + testObj.AGE; }); </script> </body> </html>
输出
在输入一个数字并单击“点击此处”按钮后,-
广告