0

Why we can't access a variable defined in a constructor function. Below is the given condition.

    var getEmployee = function(name){
                var usrId = 9;
                this.name = name;
            }
    var emp = new getEmployee("Karlie Kloss");
    console.log(emp.usrId);

2 Answers 2

2

You are trying to access a local variable. Variable has a scope. As you have defined variable in function (using var userId). So its scope has limited to its function. you can't access that variable outside that function.Use this instead of var.

var getEmployee = function(name) {
    this.usrId = 9;
    this.name = name;
}

var emp = new getEmployee("Karlie Kloss");
console.log(emp.usrId);

You can study about variable scope here:- https://learn.microsoft.com/en-us/scripting/javascript/advanced/variable-scope-javascript

Sign up to request clarification or add additional context in comments.

Comments

0

This is because the variable usrIdis declared with var: so it is not "attached" to the object.

To do so, you have to use this instead of var, like this:

var getEmployee = function(name) {
    this.usrId = 9;
    this.name = name;
}

var emp = new getEmployee("Karlie Kloss");
console.log(emp.usrId);

The keyword var makes the varaible scoped to the parent "top-block" (e.g. function), so it is not visible outside it.

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.