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

后端 未结 8 1179
野趣味
野趣味 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:47

    In a javascript static function, you can call new this() like so,

    var Class = function(){}; // constructor
    Class.foo = function(){return this;} // will return the Class function which is also an object
    

    Therefore,

    Class.foo = function(){ return new this();} // Will invoke the global Class func as a constructor
    

    The moral of the story is, not to forget functions are just like any other objects when you are not calling them.

提交回复
热议问题