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

时间:2012-03-11 11:33:45

标签: javascript this

为什么这指向父类,而不指向窗口对象? 这不是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 ?

2 个答案:

答案 0 :(得分:1)

Two.value instanceof Class // true

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

答案 1 :(得分:0)

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"