简体   繁体   中英

Return value of this from Javascript constructor function, when another constructor is returned

Why is this pointing to parent Class, and not to window object ? Not this inside of Klass function.

function Class() {
    function Klass() {
        this.color="blue"
    }
    Klass.prototype.value = this; // when called this is pointing to Class
    console.log(this) // "Class"
    return Klass;
}

var One = new Class(); // new constructor is returned
var Two = new One(); // creating new object
Two.value 
    - Class  // why ?
Two.value instanceof Class // true

Two.value包含Class的实例,而不是对该Class的引用。

function Class() {
    function Klass() {
        this.color="blue"
    }
    Klass.prototype.value = this; // this is in a closure
    console.log(this) // "Class"
    return Klass;
}

var One = new Class(); // new constructor is returned
var Two = new One(); // creating new object
Two.value 
    - Class  // this is always refer to "One"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM