Miroslav Trninic
Miroslav Trninic

Reputation: 3455

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 ?

Upvotes: 0

Views: 193

Answers (2)

Torrent Lee
Torrent Lee

Reputation: 845

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"

Upvotes: 0

Vadim Baryshev
Vadim Baryshev

Reputation: 26219

Two.value instanceof Class // true

Two.value contains instance of Class, not a reference to the Class.

Upvotes: 1

Related Questions