Object Descriptor
2018/02/03
Read From:
What are the
compositions of property?
Compositions of property
- Key
- Value
var obj = {
key: 'value'
}More Precisely
- Key
- Characteristic
var obj = {
key: 'value'
}More Precisely
- Key
- Characteristic
var obj = {
key: 'value'
}What are
property characteristics?
Six characteristics
-
writable
-
configurable
-
enumerable
-
value
-
get
-
set
Get property characteristics
var obj = { prop1: 'prop1', prop2: 'prop2' };
Object.getOwnPropertyDescriptor(obj, 'prop1', 'prop2');
// {
// value: "prop1",
// writable: true,
// enumerable: true,
// configurable: true
// }Object.getOwnProperyDescriptor(obj, 'prop');
Test
Literals
Set property characteristics
Property Descriptor
After ES5
Property Descriptor
var obj = {};
Object.defineProperty(obj, 'prop', {
value: 'This is prop',
writable: false,
configurable: true,
enumerable: true
});
console.log(obj.prop); // "This is prop"Object.defineProperty(obj, 'prop', descriptor);
Properties Descriptor
var obj = {};
Object.defineProperties(obj, {
'prop1': {
writable: false,
configurable: true,
enumerable: true,
value: 'This is prop1'
},
'prop2': {
writable: false,
configurable: true,
enumerable: true,
value: 'This is prop2'
}
});
console.log(obj.prop1); // "This is prop1"
console.log(obj.prop2); // "This is prop2"Object.definedProperties(obj, properties);
Writable
Read-only or not
Configurable
can re-config or not
can delete or not
Configurable
How about Global variable?
( they're window properties )
Enumerable
included when property iterated or not
Check Enumerable
- for..in
- obj.propertyIsEnumerable
- Object.keys(obj)
Value
Property Descriptors
Effects only on self-owned property
var obj = {},
innerObj = { innerProp: 'This is innerProp' };
Object.defineProperty(obj, 'prop1', {
value: innerObj,
writable: false,
configuration: true,
enumerable: true
});
obj.prop1 = {};
console.log(obj.prop1); // { innerProp: "This is innerProp" }
obj.prop1.innerProp = 'innerProp changed!';
console.log(obj.prop1); // { innerProp: "innerProp changed!" }getter & setter
Two declare ways:
-
Object literal
-
Property descriptor
getter & setter
Cooperate
( with a container )
Accessor descriptor
getter & setter
Data Descriptor
A property which has value
value & writable
Data descriptor
vs
Accessor descriptor
var obj = {}
Object.defineProperty(obj, 'prop1', {
get: function() {
return 'This is prop1';
},
value: 'test',
writable: true
}); // Uncaught TypeError: Invalid property descriptor. Cannot both specify accessors and a value or writable attribute, #<Object>Let's make a little wheel
Two-way binding
Two-way binding
Container:Dom elements
// HTML
<input type="text" id="myInput">// JS
var obj = {
_myInput_ : document.getElementById('myInput'),
get input() {
return this._myInput_.value;
},
set input(value) {
this._myInput_.value = value;
}
}
obj.input = 'hey';
// type something into input
console.log(obj.input);Thanks !!
JavaScript - Object Descriptor
By Chang Henry
JavaScript - Object Descriptor
- 19