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
/* 已知对象A = {name: 'sfd', getName: function(){console.log(this.name)}}, 现要求⽤不同⽅式对A进⾏改造实现A.name发⽣变化时⽴即执⾏A.getName */
The text was updated successfully, but these errors were encountered:
Sorry, something went wrong.
// 方法一 let _name = '123'; const A = { get name(){ return _name }, set name(name){ _name = name; this.getName(); }, getName() { console.log(this.name); } } A.name = 'james'; A.name = 'robin'; // 方法二 function defineReactive(obj, key, val) { if (typeof obj !== 'object' || obj === null) return; Object.defineProperty(obj, key, { get() { return val; }, set(newVal) { if (newVal === val) return; val = newVal; typeof obj.getName === 'function' && obj.getName(); } }); } const A = { name: 'sfd', getName: function () { console.log(this.name) } }; defineReactive(A, 'name'); A.name = 'james'; A.name = 'robin'; // james // robin // 方法三 const A = { name: 'sfd', getName: function () { console.log(this.name) } }; function defineReactive(obj, customKey, val) { const handler = { get(target, key, receiver) { const res = Reflect.get(target, key, receiver); return res; }, set(target, key, value, receiver) { const res = Reflect.set(target, key, value, receiver); if (key === customKey && typeof obj.getName === 'function') obj.getName(); return res; } }; const observer = new Proxy(obj, handler); return observer; } const _A = defineReactive(A, 'name'); _A.name = 'james'; _A.name = 'robin'; // james // robin
No branches or pull requests
The text was updated successfully, but these errors were encountered: