标签:targe for fine val config attrs conf div 赋值
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> </body> </html> <script> /* defineProperties 可以定义属性访问器 如果使用了value,就不能使用set,get的方法 enumerable:true 是可以使用for in 枚举出来的 configurable:true 是否可以修改value值 在传入的对象里写对象会被赋值undefined 如:defineObj["___private"]={},___private键值为undefined 使用defineProperties方法可以监听数据的更改 */ function bindData(obj,opt){ var defineObj={}; for(var attrs in obj){ defineObj["___"+attrs]={ value:obj[attrs], writable: true, enumerable: true, configurable: true }; (function(attrs){ defineObj[attrs]={ set: function (x) { this["___"+attrs]=x; opt.getFn&&opt.getFn(x,attrs); }, get: function () { opt.setFn&&opt.setFn(this["___"+attrs],attrs); return this["___"+attrs]; }, enumerable: false, configurable: true } })(attrs); } Object.defineProperties(obj,defineObj); } //测试数据 var model={a:"w",b:2}; bindData(model,{setFn:setFn,getFn:getFn}); function setFn(val,attr){ console.log("setFn:"+attr+":"+val); } function getFn(val,attr){ console.log("getFn:"+attr+":"+val); } </script>
标签:targe for fine val config attrs conf div 赋值
原文地址:http://www.cnblogs.com/zhangzhicheng/p/7487663.html