Class keyword in Javascript

前端 未结 7 1596
时光取名叫无心
时光取名叫无心 2020-12-03 04:17

According to this article it should be a Javascript 2.0 way to define class. However, I never saw that in practice. Thus the question. How to use class keyword and what is t

7条回答
  •  孤街浪徒
    2020-12-03 05:05

    Summary

    In ES6 the class keyword was introduced. The class keyword is no more than syntactic sugar on top of the already existing prototypal inheritance pattern. Classes in javascript is basically another way of writing constructor functions which can be used in order to create new object using the new keyword.

    Example

    class Person {
    
      constructor(name) {
        this.name = name;
      }
      talk() { console.log('hi'); }
    }
    
    const me = new Person('Willem');
    
    console.log(typeof Person) 
    // logs function, Person class is just another constructor function under the hood
    
    console.log(me.__proto__ === Person.prototype) 
    // logs true, classes just use the same prototypal inheritance pattern which is used by constructor functions. 
    // An object created with the new keyword gets a __proto__ property on it which is a reference to the prototype property on a constructor function.

    In the above sample there can be observed in the first log that classes create from the class keyword actually are functions under the hood.

    console.log(typeof Person) // logs 'function'
    

    es6 classes use the same prototypal inheritance pattern which is used by constructor functions. Here is another example to demonstrate this behavior:

    class Dog {
    
      constructor (name) {
          this.name = name;
      }
      
      bark () { console.log('bark') };
    
    }
    
    let doggie = new Dog('fluffy');
    
    doggie.bark(); // logs bark
    
    
    Dog.prototype.bark = () => console.log('woof');  
    // changing the prototype of Dog, doggie refers to this with its __proto__ property. 
    //Therefore doggie bark method has also changed.
    
    
    doggie.bark(); // logs woof

    The takeaway in the above example is that the bark method of any dog instance can be changed at runtime. This is because the bark method of any object created with the Dog class is just referring to this function.

提交回复
热议问题