Confusing JavaScript statement: “var x = new this();”

后端 未结 8 1029
野趣味
野趣味 2021-02-01 20:30

I thought I understood the concept of the JavaScript prototype object, as well as [[proto]] until I saw a few posts regarding class inheritance.

Firstly, \"JavaScript OO

相关标签:
8条回答
  • 2021-02-01 20:56

    this() refers to the the function that the code is in, but this() would have to be within that function. Calling new this(); within a function would create a never ending loop. Calling it outside of a function would be redundant because there is no function/class set as this().

    0 讨论(0)
  • 2021-02-01 21:00

    A simpler code explaination:

    class User {
      constructor() {
        this.name = '';
        this.age = '';
      }
      static getInfo() {
        let user = new this();
        console.log(user);
      } 
    }
    
    User.getInfo()
    

    Output:

    Object {
      age: "",
      name: ""
    }
    
    0 讨论(0)
提交回复
热议问题