Object.defineProperty - garevna/js-course GitHub Wiki
• Object.assign()
• Object.create()
Этот метод позволяет создать объекту свойство с дескриптором
- Первый аргумент метода - ссылка на объект, которому добавляется свойство
- Второй аргумент - имя свойства ( строка )
- Третий аргумент - объект дескриптора свойства
☕ 1️⃣
Добавим свойство type объекту sample и сделаем это свойство неперечислимым
var sample = {
name: "figure",
size: 100,
color: "red"
}
Object.defineProperty ( sample, 'type', {
value: "svg",
enumerable: false
})
Object.keys ( sample )► (3) ["name", "size", "color"]☕ 2️⃣
Добавим еще одно свойство объекту sample
Свойство operation будет с геттером и сеттером
get() и set() в дескрипторе свойства, нельзя использовать атрибуты writable и value
Object.defineProperty ( sample, "operation", {
get: () => this.operation ?
this.operation.substr ( 0, 1 ) : "?",
set: newVal => this.operation = newVal + "***"
})▼ {name: "figure", size: 100, color: "red", type: "svg"}
color: "red"
name: "figure"
size: 100
operation: (...)
type: "svg"
► get operation: () => {…}
► set operation: newVal => this.operation = newVal + "***"
► __proto__: Object☕ 3️⃣
var course = 28
var thing = {
name: "Утюг",
mark: "Tefal",
priceUSD: 20
}
Object.defineProperty ( thing, "priceUAH", {
get: function () {
return this.priceUSD * course
},
set: function ( newPriceUAH ) {
this.priceUSD = newPriceUAH / course
}
})
console.log ( thing.priceUAH )560Теперь выполним присваивание значения вычисляемому свойству ( вызывая под капотом сеттер этого свойства ):
thing.priceUAH = 450
console.log ( thing.priceUDS )8.928571428571429Выведем в консоль дескриптор вычисляемого свойства priceUAH
console.log (
Object.getOwnPropertyDescriptor ( thing, "priceUAH" )
)▼ {get: ƒ, set: ƒ, enumerable: true, configurable: true}
configurable: true
enumerable: true
► get: ƒ priceUAH()
► set: ƒ priceUAH( newPriceUAH )
► __proto__: Object• Object.defineProperties()
• Object.entries()
• Object.freeze()
• Object.getOwnPropertyDescriptor()
• Object.getOwnPropertyDescriptors()
• Object.getOwnPropertyNames()
• Object.getOwnPropertySymbols()
• Object.getPrototypeOf()
• Object.is()
• Object.isExtensible()
• Object.isFrozen()
• Object.isSealed()
• Object.keys()
• Object.preventExtensions()
• Object.seal()
• Object.setPrototypeOf()
• Object.values()