3

Trying to create a class in JS with the attribute weight in the following code:

function Foo() {
    var weight = 10;
    console.log(weight);
}

When I instantiate it with var bar = new Foo();, 10 is logged to the console.

When I later call console.log(bar.weight);, undefined is logged to the console. Why is that? I was under the impression that the attributes declared within a JS class were public by default?

3
  • A variable is not a property. Commented Mar 1, 2015 at 21:35
  • 2
    This is not Java, you have to use this.weight explicitly. Commented Mar 1, 2015 at 21:36
  • 1
    var always declares a variable in that scope, no matter how or where a function is called. Commented Mar 1, 2015 at 21:52

2 Answers 2

6

That's because you haven't actually set weight as a property of bar; it's merely a local variable created upon the constructor call (this differs from some other languages, like Java, for example). To create it as a property, you need to use the keyword this:

function Foo() {
    this.weight = 10;
}

That sets weight to be a property of Foo objects, including bar, so you should be able to use console.log(bar.weight) without issue.

function Foo() {
  this.weight = 10;
}

var bar = new Foo();

document.body.innerHTML = "<code>bar</code>'s weight property is equal to " + bar.weight + ".";

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

1 Comment

Thanks. Basically the same answer as everybody else. But I think this one was the best. (Accepting when the time limit is passed)
3

Because weight is not property of Food but a local variable, Change

var weight = 10;

to

this.weight = 10;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.