「JavaScriptの理解を深めた人がさらにもう一歩先に進むための本」読んだ

最後まで読んだ。
前の本も含めて、傍に置いておきたい。


Chapter7 のプロパティ属性は全く知らなかった!
だけど、これは使うのかな?仕組み的にはすごいとは思うけど、ここまでやる?

let human = {};

Object.defineProperties(human, {
  _name: {
    value: 'igarashi',
    writable: true,
    configurable: false
  },
  name: {
    get: function() {
      return this._name;
    },
    set: function(val) {
      this._name = val;
    },
    enumerable: true,
    configurable: true
  }
});

for (let prop in human) {
  console.log(prop); // => name
}

console.log(human.name); // => igarashi 

let descriptor = Object.getOwnPropertyDescriptor(human, '_name');
console.log(descriptor.value); // => igarashi
console.log(descriptor.enumerable); // => false
console.log(descriptor.configurable); // => false
console.log(descriptor.writable); // => true

それは Chapter8 についてもそう。JavaScripter に聞きたいところ。

let human = {
  name: 'igarashi'
};

console.log(Object.isFrozen(human));

human.sex = 'M';
human.age = 35;

Object.freeze(human);

human.age = 36; // エラー

例外処理はあると嬉しいけど、コスト高とのこと。

try {
  hoge;
} catch(e) {
  console.log(e.message); // => hoge is not defined
  console.log(e instanceof Error); // => true
  console.log(e instanceof ReferenceError); // => true
} finally {
  console.log('end');
}

Chapter9 でクラスを扱ったが、やはり便利。Chapter8 と一緒に使うこともあるのかな?

class Phone {
  constructor(name) {
    this.name = name;
  }
  call() {
    console.log('発信します');
  }
}

class SmartPhone extends Phone {
  constructor(name, type) {
    super(name);
    this.type = type;
    this.callCount = 0;
  }
  showInfo() {
    console.log(`Name: ${this.name} type:${this.type}`);
  }
  call() {
    super.call();
    this.callCount++;
  }
}

let myPhone = new SmartPhone('X', 'Y');
myPhone.showInfo(); // => Name: X type:Y
myPhone.call(); // => 発信します
console.log(myPhone.callCount); // => 1