Skip to content Skip to sidebar Skip to footer

Why Is The Variable Declared Inside The Js Class `undefined`

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

Solution 1:

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.

functionFoo() {
  this.weight = 10;
}

var bar = newFoo();

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

Solution 2:

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

var weight = 10;

to

this.weight = 10;

Post a Comment for "Why Is The Variable Declared Inside The Js Class `undefined`"