存取器
2015-09-28 17:23
302 查看
/* * 一旦定义了取值函数get(或存值函数set),就不能将writable设为true,或者同时定义value属性,否则会报错 * 存取器往往用于,某个属性的值需要依赖对象内部数据的场合 */ function Loading() { Object.defineProperty(this, 'text', { get: function() { return document.querySelector('#text').textContent }, set: function(v) { if (typeof v !== 'string') { throw new Error('Non expected value') } else { document.querySelector('#text').textContent = v } } }) } var loading = new Loading() console.log(loading.text) loading.text = 'aaaa' console.log(loading.text) var o = { $n: 5, get next() { return this.$n++ }, set next(n) { if (n >= this.$n) this.$n = n else throw '新的值必须大于当前值' } } console.log(o.next) // 5 o.next = 10 console.log(o.next) // 10
相关文章推荐
- tries
- Autofac+Log4net依赖注入步骤
- POJ 3714 Raid(求两集合之间的最近点对)
- short s1 = 1; s1 = s1 + 1;有什么错? short s1 = 1; s1 += 1;有什么错?
- C#结构体特性实例分析
- nginx配置location总结及rewrite规则写法
- jQuery EasyUI Dialog拖不下来如何解决
- 第十周第一天
- Count Primes
- android 关于屏幕的设置(FullScreen、notitle)等等
- jquery-1.10.2.min.js之Multiple markers at this line
- webapp的favicon应该怎样组织代码
- js换空格为别的元素
- 一个网卡绑多个 IP: IP Alias 的测试用途(鸟哥)
- Nginx的location匹配指令及常用内置变量
- 学习笔记-java基本类型的包装类,常用方法
- Android学习:实现复杂的列表项
- 51nod 算法马拉松6(索函数)(规律题目)
- spring整合hibernate配置注解事务的相关问题
- 多线程编程——prctl()函数介绍