JavaScript class - Call method when object initialized

前端 未结 5 1309
时光取名叫无心
时光取名叫无心 2021-02-02 09:56

I have a class similar to the one below. How do I call my init method when the object is created? I don\'t want to have to create an instance of my object then call

5条回答
  •  面向向阳花
    2021-02-02 10:29

    JavaScript classes introduced in ECMAScript 2015 are primarily syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax is not introducing a new object-oriented inheritance model to JavaScript. JavaScript classes provide a much simpler and clearer syntax to create objects and deal with inheritance.

    - MDN web docs

    When using this syntax, because only the constructor() method is run on instantiation you can't auto-instantiate an object. You always have to add user = new MyUser()

    var user;
    
    class MyUser {
      constructor(var1, var2) {
    
        this.var1 = var1;
        this.var2 = var2;
    
      }
    
      static staticMethod() {
    
        // accessed directly with the class name `MyUser`
    
      }
    
      instanceMethod() {
    
        // accessed with object instance
    return true
      }
    
    }
    
    user = new MyUser('hey','there')

提交回复
热议问题