<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Object.defineProperty</title> </head> <body> <script> class Test { constructor(data) { for (let key in data) { Object.defineProperty(this, key, { configurable: false, enumerable: true, set(val) { console.log(‘设置值事件‘) data[key] = val; }, get() { console.log(‘获取值事件‘) return data[key]; } }) } } } let data = { name: ‘sweet boy‘ } let test = new Test(data); </script> </body> </html>
在浏览器中打开运行过程为
Object.defineProperty用法记录一下(很多前端框架底层实现)
原文:https://www.cnblogs.com/hello-dummy/p/13376962.html