js儲存常量,使其只可讀,實現方式有哪些

NardoLi發表於2017-11-10

儲存常量,使其只可讀,實現方式有哪些

1 . es6語法中的常量宣告符 const

const freeze = 'strange'

freeze = 'tony' //  => Uncaught TypeError: Assignment to constant variable.

如果const宣告一個物件會如何?

const freezeHero = {
    name: 'strange', 
    skill: 'magic'
    }

freezeHero = {
    name: 'no'
}   //  => Uncaught TypeError: Assignment to constant variable.

//  改變該物件的屬性
freezeHero.name = 'tony'
freezeHero.skill = 'equip'
console.log(freezeHero) //  => {name: 'tony', skill: 'equip'}

const宣告的物件屬性仍然可以改變,因為僅僅只是變數指向的那個記憶體地址不能改動。

2 . Object.freeze()

Object.freeze()同樣也是es6新增的api

const freezeMan = {
    name: 'tony'
}
Object.freeze(freezeMan)
freezeMan.name = 'strange'
freezeMan.skill = 'magic'
console.log(freezeMan)  //  => {name: 'tony'}

可以看到,物件的靜態屬性變為只讀,不可修改,且不可以新增新屬性,如果屬性本身也是物件會如何?

const freezeMen = {
    members: ['tony', 'strange'], 
    level: 2
}
Object.freeze(freezeMen)
freezeMen.level = 4
//  修改物件的members屬性
Array.prototype.push.apply(freezeMen.members, ['captain', 'hulk'])

console.log(freezeMen)  // => {members: ['tony', 'strange', 'captain', 'hulk'], level: 2}

被鎖定的物件,屬性值為簡單型別時會被freeze,但值為物件時仍然可以修改,這與const宣告符的原理一致。下面通過遞迴的方式,實現物件引用的深層次鎖定,物件的任何屬性都不可重寫,也不可動態新增新屬性

const freezeMen = {
    members: ['tony', 'strange'], 
    level: 2
}
const deepLock = function(obj){
    Object.freeze(obj)
    Object.keys(obj).map((k, i) => {
        if(typeof obj[k] === 'object'){
            deepLock(obj[k])
        }
    })
    return obj
}
deepLock(freezeMen).members = ['captian', 'hulk']
freezeMen.victory = true

console.log(freezeMen)  // => {members: ['tony', 'strange'], level: 2} 

//  如果再想通過defineProperty方法來增加新屬性,會直接丟擲異常
Object.defineProperty(freezeMen, 'lastDefine', {
    writable: false,
    value: 'it is lastDefine',
    enumerable: true
})
//  => Uncaught TypeError: Cannot define property lastDefine, object is not extensible

3 . Object.defineProperty

用這個方法實現的效果與freeze方法差不多,設定writable屬性值為只讀,對於簡單值型別有效,而屬性值本身為物件時仍然是可以修改其值的。同樣可以使用遞迴來實現

var lockProperty = function(data) {
    if(typeof data === 'object') {
        Object.keys(data).map(key => {
            defineDisWritable(data, key, data[key])
        })
    }
    return data
}
var defineDisWritable = function(obj, key, val) {
    Object.defineProperty(obj, key, {
        writable: false,
        value: val,
        enumerable: true
    })
    if(typeof val === 'object') {
        lockProperty(val)
    }
}
const freezeMen = {
    members: {
        people: {
            name: 'default'
        }
    }, 
    level: 2
}
lockProperty(freezeMen)

freezeMen.add = 'new key'
freezeMen.level = 10
freezeMen.members = {
    house: 'big'
}

freezeMen.members.people.name = 'modified'
console.log(freezeMen)  //  => {add: 'new key', members: {people: {name: 'default'}, level: 2}

// 我們試試使用defineProperty新增新屬性
Object.defineProperty(freezeMen, 'lastkey', {
    writable: false,
    value: 'last',
    enumerable: true
})
console.log(freezeMen) // => {add: 'new key', members: {people: {name: 'default'}, level: 2, lastkey: 'last'}

上述方法也可以實現物件深層巢狀的屬性凍結,與Object.freeze()的唯一區別是,傳遞的頂層物件仍然可以新增新的屬性(不管是通過動態新增還是Object.defineProperty)。

還可以通過劫持setter來鎖定通過defineProperty方法新增的屬性。

var lockProperty = function(data) {
    if(typeof data === 'object') {
        Object.keys(data).map(key => {
            defineDisWritable(data, key, data[key])
        })
    }
    return data
}
var defineDisWritable = function(obj, key, val) {
    Object.defineProperty(obj, key, {
        set: function(newVal) {
            //  不賦新值
            // val = newVal
        },
        get: function() {
            return val
        },
        enumerable: true
    })
    if(typeof val === 'object') {
        lockProperty(val)
    }
}
const freezeMen = {
    members: {
        people: {
            name: 'default'
        }
    }, 
    level: 2
}
lockProperty(freezeMen)

freezeMen.add = 'new key'
freezeMen.level = 10
freezeMen.members = {
    house: 'big'
}

freezeMen.members.people.name = 'modified'
console.log(freezeMen)  //  => {add: 'new key', members: {people: {name: 'default'}, level: 2}

_比較Object.defineProperty()Object.freeze()兩種方法的遞迴方案,對於複雜的資料物件,可以實現兩種情況:

1.要儲存一個完全不可寫的資料,使用Object.freeze();
2.要儲存一個不可修改但可擴充的資料,使用Object.defineProperty()

相關文章