-3
var course = new Object();

var course = {
  title: "JavaScript Essential Training",
  instructor: "Morten Rand-Hendriksen",
  level: 1,
  published: true,
  views: 0,
  updateViews: function() {
    return ++course.views;
  },
};

console.log(course);
console.log(course);
mplungjan
  • 169,008
  • 28
  • 173
  • 236

3 Answers3

1

You are assigning an empty object to the variable course.

var course = new Object();

Now you are assigning an object with properties into it.

var course = {
  title: "JavaScript Essential Training",
  instructor: "Morten Rand-Hendriksen",
  level: 1,
  published: true,
  views: 0,
  updateViews: function() {
    return ++course.views;
  },
};

Here an object is assigned to variable course and updateViews method will not call as this is an initialization. So if you want to update views you should call updateViews from your variable course. Like this

console.log(course.updateViews());
Aman Kumayu
  • 381
  • 1
  • 9
0

It would help if you could post what you actually see. However, surely you want to call updateViews() to change the views. Just asking it to write out the current value of the object does not call each method on the object.

Simon
  • 736
  • 6
  • 21
0

Just console.logging the object does not update the views.

Also your first declaration is not useful.

If you want you could do this:

var course = {
  title: "JavaScript Essential Training",
  instructor: "Morten Rand-Hendriksen",
  level: 1,
  published: true,
  views: 0,
  updateViews: function() {
    return ++course.views;
  },
  toString : function() { this.updateViews(); return this }
};


console.log(course.toString());
console.log(course.toString());

I found a more detailed answer

Does console.log invokes toString method of an object?

mplungjan
  • 169,008
  • 28
  • 173
  • 236