您的位置:首页 > 其它

存取器

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: