1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | var firstNameS = Symbol('firstName'); var lastNameS = Symbol('lastName'); var ageS = Symbol('age'); class Person { constructor(firstName, lastName, age) { this[firstNameS] = firstName; this[lastNameS] = lastName; this[ageS] = age; } }; var ted = new Person('Ted', 'Neward', 45); ted.sayHowdy = function() { console.log(this[firstNameS] + ' says howdy!'); }; ted.waveGoodbye = function(msg) { return '' + msg + ' Buh-bye!'; }; let handler = {}; handler.get = function(target, propName) { console.log('\nhandler.get() accessed property', propName, 'of class', target.constructor.name); return target[propName]; } handler.set = function(target, propName, newValue) { console.log('\nhandler.set() changed property', propName, 'of class', target.constructor.name, 'to', newValue); target[propName] = newValue; } ted = new Proxy(ted, handler); ted.sayHowdy(); console.log(ted.waveGoodbye('See you next time!')); ted.favoriteColor = 'green'; console.log('Ted\'s favorite color is', ted.favoriteColor); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | var firstNameS = Symbol('firstName'); var lastNameS = Symbol('lastName'); var ageS = Symbol('age'); class Person { constructor(firstName, lastName, age) { this[firstNameS] = firstName; this[lastNameS] = lastName; this[ageS] = age; } eat() { console.log('Chomp, chomp'); } }; var ted = new Person('Ted', 'Neward', 45); let handler = {}; handler.get = function(target, propName) { let original = target[propName]; if (typeof original === 'function') { console.log('\nhandler.get() invoked function', propName, 'of class', target.constructor.name); return (...args) => { console.log('Executing', propName, 'with', args); // use handler method apply() to invoke the function return original.apply(target, args); } } else { console.log('\nhandler.get() accessed property', propName, 'of class', target.constructor.name); return target[propName]; } } handler.set = function(target, propName, newValue) { console.log('\nhandler.set() changed property', propName, 'of class', target.constructor.name, 'to', newValue); target[propName] = newValue; } ted = new Proxy(ted, handler); ted.eat(); |
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) | Powered by Discuz! 7.0.0 |