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

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

    AJS.Class effectively* translates this:

    var Person = new AJS.Class({
        init: function(name) {
            this.name = name;
            Person.count++;
        },
        getName: function() {
            return this.name;
        }
    });
    Person.count = 0;
    

    into this:

    var Person = function (name) {
        this.name = name;
        Person.count++;
    };
    
    Person.prototype = {
        getName: function() {
            return this.name;
        }
    };
    
    Person.extend = AJS.Class.prototype.extend;
    Person.implement = AJS.Class.prototype.implement;
    
    Person.count = 0;
    

    Therefore, in this case, this in AJS.Class.prototype.extend refers to Person, because:

    Person.extend(...);
    // is the same as
    Person.extend.call(Person, ...);
    // is the same as
    AJS.Class.prototype.extend.call(Person, ...);
    

    * There are a lot of cases I don't go over; this rewrite is for simplicity in understanding the problem.

提交回复
热议问题