ES6-9 对象密封4种方式、assign、取值函数的拷贝
生活随笔
收集整理的這篇文章主要介紹了
ES6-9 对象密封4种方式、assign、取值函数的拷贝
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一 對象密封
1 Object.preventExtensions 禁止對象拓展,仍可刪除
- 嚴格模式下報錯
2 Object.defineProperty
const obj = {} obj.b = 1 // 屬性描述符全是true console.log(Object.getOwnPropertyDescriptor(obj, 'b')) Object.defineProperty(obj, 'c', {value: 100 // 屬性描述符全是false }) console.log(Object.getOwnPropertyDescriptor(obj, 'c'))3 Object.seal 對象密封 禁止拓展+不可刪除,仍可修改
- 嚴格模式下報錯
4. Object.freeze - 凍結的 不可增刪改
const origin = {a: 1 } const fixed = Object.freeze(origin) console.log(origin === fixed) // true console.log(Object.isFrozen(origin)) // true 凍結的 console.log(Object.isSealed(origin)) // true 密封的 console.log(Object.isExtensible(origin)) // false 不可拓展 origin.a = 100 console.log(origin) // 不可修改二 Object.is
console.log(NaN === NaN) // false console.log(+0 === -0) // true console.log(Object.is(NaN, NaN)) // true 和全等不同的 console.log(Object.is(+0, -0)) // false 和全等不同的 console.log(Object.is({}, {})) // false三 Object.assign(tar, …sources) 合并對象
const tar = {} const obj = {a: 1} const copy = Object.assign(tar, obj) console.log(copy === tar) // true // 直接使用tar-
屬性覆蓋:取后寫的
-
當tar是不能轉為對象的原始值null/undefined時,報錯
-
source能轉成對象,且屬性的可枚舉性為真,則可以合并得到新的對象
-
source為數組時
-
Object.assign拷貝的是可枚舉屬性,繼承屬性和不可枚舉屬性不可拷貝
Object.assign是淺拷貝
- 在嵌套的對象里要尤其注意
嵌套對象,同名屬性會被后者替換
console.log(Object.assign([1,2,3],[4,5])) // {0: 4, 1: 5, 2: 3}含getter
含setter
擴充原型上的方法、屬性
function Person() { } Object.assign(Person.prototype, {name: 'hh',eat() { } }) console.log(Person.prototype)設置默認項
const DEFAULT = {url: {host: 'www.baidu.com',port: 80} } function test(opt) {opt = Object.assign({}, DEFAULT, opt)console.log(opt) } test({url: { port: 8080 } }) test()四 Symbol 原始類型
- 可以看成永遠不會重復的字符串
五Object.defineProperties/getOwnPropertyDescriptors
- 獲取多個描述/定義多個屬性
- 解決Object.assign不能拷貝setter/getter的問題
- 拷貝
總結
以上是生活随笔為你收集整理的ES6-9 对象密封4种方式、assign、取值函数的拷贝的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 乐优商城个人笔记上-主要框架、基础知识、
- 下一篇: ES6-10 super、4种遍历方式、