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

后端 未结 8 1147
野趣味
野趣味 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条回答
  •  萌比男神i
    2021-02-01 20:48

    Imagine the following situation :

    var inner = function () {
        var obj = new this;
        console.log(obj.myProperty);
    };
    
    var f1 = function () {
        this.myProperty = "my Property"
    }
    
    f1.f2 = inner;
    f1.f2();
    

    Here the calling object is itself a function, so this will return a function, and we can instantiate it.

    In order to use this()(not this) the outer function(the context) must itself return smth that can be instantiated(another function):

    var inner = function () {
        var obj = new this();
        console.log(obj.myProperty);
    };
    
    var f1 = function () {
        var func = function () {};
        func.myProperty = 'my property';
        return func;
    };
    
    f1.f2 = inner;
    f1.f2();
    

提交回复
热议问题