• 对象本质: 数据结构 | 类似:hash hash-table dictionary associative array
  • 对象特性:完整的访问属性
    • 属性特性: 可写 | 可枚举 | 可设置
    • 对象特性: 对象的原型 | 对象的类 | 对象的扩展标记
    • 对象属性:自有属性 | 继承属性
  • 对象创建,属性操作 (增删查改)
  1. // 字面量形式
  2. var empty = {x:1};
  3. // 构造函数形式
  4. var fun = new Function('arg1', 'return arg1');
  5. // 原型链继承式
  6. var num = Object.create({hello: 1});
  7. // 属性访问和设置
  8. num.hello = 2;
  9. num['hello']; // 2
  10. num.defineProperty(name, {
  11. value: 'case',
  12. writable: true,
  13. enumerable: true,
  14. configurable: true
  15. });

Notice:

  1. 所有通过对象直接创建的对象都有同一个原型对象,并且可以通过Object.prototype获得对原型对象的 引用
  2. 对象只会被引用,不会被复制。
  3. hasPrototypeProperty 检查原型属性,可以 hasOwnProperty 取反

对象继承:基于原型链的继承

  1. Object.create(inheritObject.prototype);
  2. 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

js - object - 图1


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:

  1. 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
  2. 10 - the interpreted value for count (this becomes substitutions[0])
  3. "2.50" - the interpreted value for (count * price).toFixed(2) (this becomes substitutions[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.