Yotam
Yotam

Reputation: 10485

Difference between 'this' and 'var' when declaring variable, nodeJS

I have the next piece of code:

function Server() {
    this.isStarted = false;
//  var isStarted = false;

    function status() {
        return isStarted;
    }

    console.log(status());
}

var a = new Server()

When I run it I get

ReferenceError: isStarted is not defined
    at status (/a/fr-05/vol/home/stud/yotamoo/workspace/ex4/text.js:7:10)
    at new Server (/a/fr-05/vol/home/stud/yotamoo/workspace/ex4/text.js:10:14)
    at Object.<anonymous> (/a/fr-05/vol/home/stud/yotamoo/workspace/ex4/text.js:

However if I change this.isStarted = false; to var isStarted = false; everything works fine.

Does anyone care to explain why?

Thanks

Upvotes: 0

Views: 208

Answers (2)

Bogdan Kulynych
Bogdan Kulynych

Reputation: 713

Long story short. Since isStarted, when defined as this.isStarted = true, is a property of the current object (JavaScript this keyword refers to an object where the function was called), in status function you will have to access it as this.isStarted.

Declaring it as variable (var) is different. Technically, isStatus will become a property of hidden lexical scope object. You have to access it as just isStatus in the whole Server function body and and all of the child functions.

Upvotes: 0

user1882585
user1882585

Reputation: 331

This referes to the owner of something. See this article about this. Where as var declares a local variable.

In your case, you want to refer to know if a server is started, so you need to add 'this' to your status function.

function status() {
    return this.isStarted;
}

Upvotes: 2

Related Questions