We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
// 假设有一个 user 对象 // 1. 在 ES5 中可以通过 Object.defineProperty 来实现已有属性的监听 Object.defineProperty(user, 'name', { set: function (key, value) { } }) // 缺点:如果 id 不在 user 对象中,则不能监听 id 的变化 // 2. 在 ES6 中可以通过 Proxy 来实现 const user = new Proxy({}, { set: function (target, key, value, receiver) { } }) // 这样即使有属性在 user 中不存在,通过 user.id 来定义也同样可以这样监听这个属性的变化。
The text was updated successfully, but these errors were encountered:
Object.defineProperty
const obj = {}; Object.defineProperty(obj, 'data', { get(){ return data }, set(newVal) { onsole.log('我改变了') data = newVal; }, }); var obj = {}; Object.defineProperties(obj, { a: { configurable: true, //表示该属性描述符可以被改变(默认为false) get: function() { console.log('get: ',a) return a }, set: function(newValue) { a = newValue; console.log('set: ',a) } }, b: { configurable: true, get: function() { console.log('get: ',b) return b; }, set: function(newValue) { b = newValue; console.log('set: ',b) } } })
Proxy
const newObj = new Proxy({},{ get: function(obj, prop) { return prop in obj ? obj[prop] : null; }, set(newVal){ console.log(newVal) console.log('我改变了') return true } });
Sorry, something went wrong.
No branches or pull requests
The text was updated successfully, but these errors were encountered: