<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> div{ width: 50px; height: 50px; background-color: aqua; } </style> </head> <body> <div></div> <input type="text" id="text"> <script> var obj=function () { var _c=0; return{ a:1, b:2, set c(value){ console.log(value+"调用了set"); _c=value+this.a+this.b }, get c(){ console.log(_c+"调用了get") return _c } } }(); obj.c=2; console.log(obj.c) var div=document.querySelector("div"); var texts=document.querySelector("#text"); texts.addEventListener("blur",blurHandler); div.addEventListener("click",clickHandler); function clickHandler(e) { obj1.sum=1; } function blurHandler(e) { obj1.sum=this.value; } var obj1=(function () { var _sum=0; return { set sum(value){ if(isNaN(Number(value))) return; _sum+=Number(value); div.textContent=_sum; }, get sum(){ return _sum; } } })(); </script> </body> </html>
js 访问器 setter getter
最新推荐文章于 2022-08-09 19:53:13 发布