存取器

/*
 * 一旦定义了取值函数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
原文地址:https://www.cnblogs.com/jzm17173/p/4844522.html