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,101
  • 20
  • 56
  • 70
Einar Sundgren
  • 4,275
  • 8
  • 38
  • 57

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
  • 572,313
  • 128
  • 898
  • 1,281
AstroCB
  • 12,101
  • 20
  • 56
  • 70
3

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

var weight = 10;

to

this.weight = 10;
Ahmad
  • 1,838
  • 13
  • 19