简体   繁体   English

当返回另一个构造函数时,此值从Javascript构造函数返回

[英]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. 这不是Klass函数的功能。

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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