1

JavaScript ES6 Class

 2 years ago
source link: https://kim85326.github.io/2019/09/13/JavaScript-ES6-Class/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

JavaScript ES6 Class


  • JavaScript 並沒有提供物件導向的語法,而是透過 function 來建立物件

    function Person(name, age) {
      this.name = name;
      this.age = age;
    }
    
    Person.prototype.sayHi = function() {
      console.log("Hi! " + this.name);
    };
    
    const person1 = new Person("Elaine", 18);
    person1.sayHi(); // "Hi! Elaine"
    
  • ES6 建立物件

    • 在 ES6 中的 Class 語法,也並不是真的是以類別為基礎的物件導向
    • 在骨子裡仍然是以原型為基礎的物件導向
    • 它只是個語法糖
    • 加入 Class 語法的目的,並不是要建立另一套物件導向的繼承模型,而是為了提供更簡潔的語法來作物件建立與繼承
    class Person {
      constructor(name, age) {
        this.name = name;
        this.age = age;
      }
    
      sayHi() {
        console.log("Hi! " + this.name);
      }
    }
    
    const person1 = new Person("Elaine", 18);
    person1.sayHi(); // "Hi! Elaine"
    

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK