JavaScriptのハード部分をマスターする



ES 6クラスの使用

演習8

Create a class PersonClass. PersonClass should have a constructor that is passed an input of name and saves it to a property by the same name. PersonClass should also have a method called greet that logs the string 'hello'.


class PersonClass {
  constructor() {
    // add code here
  }

  // add code here
}
const george = new PersonClass();
george.greet();
// -> Logs 'hello'

ソリューション8
class PersonClass {
  constructor(name) {
    this.name = name;
  }

  greet() {
    console.log("hello");
  }
}
運動2と5の正確なレクリエーションclass パターン.他の言語から来ている人々のために読みやすく、多くのJSディアーズは、このパターンはJSにネイティブに見えないと文句を言う.効果的に、JSエンジンは、運動5で正確に何をしています.

運動9

Create a class DeveloperClass that creates objects by extending the PersonClass class. In addition to having a name property and greet method, DeveloperClass should have an introduce method. When called, introduce should log the string 'Hello World, my name is [name]'.


const thai = new DeveloperClass("Thai", 32);
console.log(thai.name);
// -> Logs 'Thai'
thai.introduce();
//-> Logs 'Hello World, my name is Thai'

解決9
class DeveloperClass {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  introduce() {
    console.log(`Hello World, my name is ${this.name}`);
  }
}
これはもちろんエクササイズ7のようですが、プロトタイプのプロパティに直接メソッドを追加する代わりにクラス構文を使用します.再び、舞台裏では、JSエンジンは全く同じ操作を実行します.