0

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

2 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.