- 对象本质: 数据结构 | 类似:
hash
hash-table
dictionary
associative array
- 对象特性:完整的访问属性
- 属性特性: 可写 | 可枚举 | 可设置
- 对象特性: 对象的原型 | 对象的类 | 对象的扩展标记
- 对象属性:自有属性 | 继承属性
- 对象创建,属性操作 (增删查改)
// 字面量形式
var empty = {x:1};
// 构造函数形式
var fun = new Function('arg1', 'return arg1');
// 原型链继承式
var num = Object.create({hello: 1});
// 属性访问和设置
num.hello = 2;
num['hello']; // 2
num.defineProperty(name, {
value: 'case',
writable: true,
enumerable: true,
configurable: true
});
Notice:
- 所有通过对象直接创建的对象都有同一个原型对象,并且可以通过Object.prototype获得对原型对象的 引用 。
- 对象只会被引用,不会被复制。
in
for..in
hasOwnProperty
propertyIsEnumerable
in Object.keys
in Object.getOwnPropertyNames
它们能够访问对象数据的类型。- Enumerability and ownership of properties
hasPrototypeProperty
检查原型属性,可以hasOwnProperty
取反
对象继承:基于原型链的继承
Object.create(inheritObject.prototype);
Object.prototype.toString.call(0).slice(8,-1); // Type of constructor
Object对象方法
object.toString();
object.toLocalString();
object.valueOf();
Object.defineProperty(obj, name, {
value: 'v',
configurable: true, // 表示能够修改该属性名 delete
enumerable: true, // for-in 循环中是否返回属性
writable: true, // 表示能否修改属性值
get: getter,
set: setter
});
Object.defineProperties()
Object.create()
Object.clone()
Object.seal() // preventExtensions and configurable: false
Object.freeze() // seal() + writable: false
Object.assign({}, myboj)
...
JSON.stringify();
JSON.parse();
Getter / Setter
Notice:
- 避免在枚举期间修改对象
- 如果需要修改应该使用
for / while
循环而不是for...in
循环 - 不能够在
Object.prototype
中增加可枚举属性,会导致 原型污染 - 利用
null
标明, 利用hasOwnProperty
防止原型污染
Template String
// Template String
let html = `
<div>
<h1>Title</h1>
</div>`.trim();
// Substitutions
let count = 10,
price = 0.25,
message = `${count} items cost $${(count * price).toFixed(2)}.`;
console.log(message); // "10 items cost $2.50."
// Taged Template
let count = 10,
price = 0.25,
message = passthru`${count} items cost $${(count * price).toFixed(2)}.`;
If you had a function called passthru()
, that function would receive three arguments:
literals
, containing:""
- the empty string before the first substitution" items cost $"
- the string after the first substitution and before the second"."
- the string after the second substitution
10
- the interpreted value forcount
(this becomessubstitutions[0]
)"2.50"
- the interpreted value for(count * price).toFixed(2)
(this becomessubstitutions[2]
)
// Using Raw Values
let message1 = `Multiline\nstring`,
message2 = String.raw`Multiline\nstring`;
console.log(message1); // "Multiline
// string"
console.log(message2); // "Multiline\\nstring"
Best Practice
Use Getters / Setters.
Use closure to hide inner implementations.