JavaScript-物件(Object)與物件導向

  1. 物件

    什麼是物件?

    物件 object = 一個東西=屬性+行為

    建立與使用物件
    let hero = {
      //key = power,age
      //value = 100,20
      power: 100,
      age: 20,
      attack: function () {
        console.log("hi");
      },
    };
    console.log(hero); //{ power: 100, age: 20 }
    console.log(hero.age); //20
    
    修改、新增、刪除

    相比於 Ruby,JavaScript 在物件上可以在外部直接進行,舉例如下

    let hero = {
      power: 100,
      age: 20,
      attack: function () {
        console.log("hi");
      },
    };
    //修改
    hero.age = 18;
    console.log(hero.age); //18
    //新增屬性,要小心使用
    hero.hello = 124;
    console.log(hero); //{ power: 100, age: 18, attack: [Function: attack], hello: 124 }
    //刪除屬性
    delete hero.age;
    console.log(hero); //{ power: 100, attack: [Function: attack], hello: 124 }
    
    其他使用

    1.當外部宣告的變數與常數和物件裡的 key 同名時

    const age = 18;
    const attack = () => {
      console.log("hi");
    };
    
    let hero = {
      power: 100,
      age, //只寫一個代表key與value是一樣的命名,但外面要有同名的宣告變數或常數
      attack,
    };
    
    1. 用解構取出物件所有資料
    const obj = {
      power: 100,
      age: 123,
    };
    const { age, power } = obj; //解構(拆解)=>常用
    console.log(age);
    console.log(power);
    //把上面名為obj的物件拆解後指定給另一個{age,power}常數
    //因為{age,power}常數與裡面有同名的key,所以可以直接把資料印出來
    
  2. 物件導向

    1. 在 JavaScript 裡,所有物件都有__proto__
    const hero = {
      name: "kk",
      power: 100,
    };
    

    從上兩張圖可知,我們創建的物件本身只有 key 與 value 沒有方法,是透過 _proto__裡的方法借來使用,不需要完整的打完hero.__proto__.toString()只要hero.toString()就可以使用該方法。

    Object.create()使用現有對像作為新創建對象的原型*(以此來做更一步的說明)*
    //創建了一個新物件
    const hero = {
      name: "kk",
      power: 100,
    };
    //以hero物件,為a物件的原型
    const a = Object.create(hero);
    

    單看 a 裡面是空物件,但每個物件都有__proto__,所以從a.__proto__中可以看到我所創建的 hero 物件,所以當使用Object.create()其實是將此物件加進去,使後來創建的物件可以使用該物件,即使後來創建的物件沒有該內容或方法。

    1. 所有 function 都有 prototype
    function heroCreator(name, power) {
      //this->{}有new會做
      this.name = name;
      this.power = power;
      //return this會自動回傳
    }
    const h1 = new heroCreator("kk", 100); //有new會創建一個空物件,有物件就有__proto__,物件導向
    const h2 = heroCreator("kk", 100); //沒有new是function,沒有回傳值不會回傳東西
    
    console.log(h1); //name:kk,power:100
    console.log(h2); //undefined
    
    heroCreator.prototype.attack = function () {
      console.log(1111);
    };
    

    我創建了一個 function,所有 function 都有 prototype,當我用 new 時會創建一個空物件,該物件的__proto__在這個時候會自動轉向prototype,所以在 prototype{ }加上行為,__proto__也可找得到,等於 ruby 的開放類別,我可以在原有的類別加上方法。

  3. Es6 後新增了語法糖衣 class
    class heroCreator {
      constructor(name, power) {
        this.name = name;
        this.power = power;
      }
      attack() {
        console.log("attack!!");
      }
    }
    
    const h1 = new heroCreator("kk", 100);
    console.log(h1); //heroCreator { name: 'kk', power: 100 }
    h1.attack(); //attack!!
    

    從 Es6 後的物件導向會以此為主要寫法。

comments powered by Disqus