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?

AstroCB
  • 12,337
  • 20
  • 57
  • 73
Einar Sundgren
  • 4,325
  • 9
  • 40
  • 59

2 Answers2

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 + ".";
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
AstroCB
  • 12,337
  • 20
  • 57
  • 73
  • Thanks. Basically the same answer as everybody else. But I think this one was the best. (Accepting when the time limit is passed) – Einar Sundgren Mar 01 '15 at 21:40
3

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

var weight = 10;

to

this.weight = 10;
Ahmad
  • 1,913
  • 13
  • 21