David Alan Condit
David Alan Condit

Reputation: 1253

Why does my constructor's "this" variable stay private?

I'm making a simple JS tree library, so I can dynamically create markup for hierarchical data.

Question: Why does "var that = this;" stay private, when I use the Tree constructor to return a new object instance? I'm glad "that" is private, but I don't know WHY it's private. Thoughts?

function Tree(data, containerId) {
    var that = this; // Private variable. Not returned by constructor, because... ???

    this.data = data;
    this.container = document.getElementById(containerId);
    this.selectedNodeId = null;
    this.container.addEventListener('click', function (e) { 
        that.selectedNodeId = e.target.getAttribute('id');
        console.log(that.selectedNodeId);
    });
}

Upvotes: 1

Views: 85

Answers (2)

Ben Aston
Ben Aston

Reputation: 55739

new Tree(...) will return the value of that (and this). Simply invoking Tree(...) will not.

The new operator returns the resulting object (ie. this) if nothing is explicitly returned. Simply calling the function will (in this case) return undefined.

Upvotes: 1

NewZeroRiot
NewZeroRiot

Reputation: 552

Take a look at closures, anything defined in a Javascript function remains in there. There are loads of great resources such as https://github.com/getify/You-Dont-Know-JS

Closures is covered in depth :)

Upvotes: 1

Related Questions