FAZA
FAZA

Reputation: 23

JavaScript / Constructor Functions

I'm still learning JavaScript. Not able to get past this:

  function Fruits(category, berries, notberries) {
      this.category = category;
      this.berries = [];
      this.notberries = [];
  }

  let f = new Fruits("fresh", ["strawberry", "raspberry"], ["apple", "mango"]);

  console.log(f); // Fruits {category: "fresh", berries: Array(0), notberries: Array(0)}

  f.category;  //"fresh"

  f.berries; //[]

Why is it not logging the values of berries and instead returning an empty array ?

Upvotes: 0

Views: 42

Answers (2)

Ele
Ele

Reputation: 33726

You need to assign the arguments to the proper attributes.

function Fruits(category, berries, notberries) {
  this.category = category;
  this.berries = berries;
  this.notberries = notberries;
}

let f = new Fruits("fresh", ["strawberry", "raspberry"], ["apple", "mango"]);

console.log(f); // Fruits {category: "fresh", berries: Array(0), 
f.category;
f.berries;

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1073978

Nothing in your constructor ever assigns the parameter berries to the property this.berries (or copies its content); the same for notberries.

To assign:

function Fruits(category,berries,notberries) {
    this.category = category;
    this.berries = berries;          // ***
    this.notberries = notberries;    // ***
}

To copy (shallow, which is fine, these are arrays of strings):

function Fruits(category,berries,notberries) {
    this.category = category;
    this.berries = berries.slice();          // ***
    this.notberries = notberries.slice();    // ***
}

The difference is that if you assign, then the object has a reference to the array that was passed in, and so does the calling code; if the calling code modifies that array, it affects the object (since they share the array). If you copy the contents of the array, then the calling code and the object each have their own array, so changes to one don't affect the other.

Both can be correct, you just need to be aware of the distinction.

Upvotes: 0

Related Questions