1.4.Object

  • 在JS中, 物件具有指向委託原型(delegate prototype)的內部參考

  • 所有的數據都是對象(javascript中除了字元串字面量、數字字面量、true、false、null、undefined之外,其他值都是對象)

  • 要得到一個對象,不是通過實例化類,而是找到一個對象作為原型並複製它

  • 當物件要求方法及特性時, JS引擎會先檢查該物件, 如果請求之鍵不在物件身上, 他就會去檢查委托原型, 此原型練通常會結束於object.

  • 1.Object.create(): ES5後被建立

    • 傳入一個參數,Object.create將會建立此參數的副本

    • (1) 如果改變實例上的特性(的值)或陣列特性,該變更將於原型上被共用

    • (2) 如果替換實例上的整個特性,該變更只會被反映在該實例上

    • example:

      var switchPotato = {
        state: false;
        isOn: function isOn{
          return this.state;
        },
        toggle: function toggle(){
          this.state = !this.state;
          return this;
        },
        meta: {
          name: 'light switch'
        }
      },
      switch1 = Object.create(switchPotato),
      switch2 = Object.create(switchPotato);
      
      test('Prototype mutations', function(){
          switch2.meta.name = 'Breaker switch';
      
          equal(switch1.meta.name, 'Breaker switch', 'Object and array mutations are shared');
      
          switch2.meta = {name : 'Power switch'};
      
          equal(switch1.meta.name, 'Breaker switch', 'Property replacement is instance-specific');
      });
  • 2.使用new調用建構子

Last updated