Sarun Dahal
Sarun Dahal

Reputation: 377

How to store returned value of an Anonymous function to a Variable in JavaScript?

I am extremely new to JavaScript so please bear with me on this one. Here is a snippet of my code:

function Course(title, instructor, views){

  this.title= title;
  this.instructor = instructor;
  this.views = views;
  this.updateViews = function() {
    return ++this.views;
  };

}

var course1 =   new Course('JS', 'Sarun', 0);

console.log(course1.updateViews);

On execution however, I had expected the value of course1.updateViews to be 1. Instead, I get the entire function displayed in the console as follows:

ƒ () {
    return ++this.views;
  }

I am sure that this is a beginner's mistake. So can anyone please Correct me on this?

Upvotes: 1

Views: 1462

Answers (2)

Luong Dinh
Luong Dinh

Reputation: 569

Because in the Course object, you declared this.updateViews as function. if you wanna get return value of function, you need to invoke that by calling:

console.log(course1.updateViews());

if you wanna updateViews is static attribute you can change the way to declare this:

function Course(title, instructor, views){

  this.title= title;
  this.instructor = instructor;
  this.views = views;
  this.updateViews = ++this.views;

}

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68393

So can anyone please Correct me on this?

You need to invoke the function using ()

console.log(course1.updateViews());

function Course(title, instructor, views){

  this.title= title;
  this.instructor = instructor;
  this.views = views;
  this.updateViews = function() {
    return ++this.views;
  };

}

var course1 =   new Course('JS', 'Sarun', 0);

console.log(course1.updateViews());

Upvotes: 4

Related Questions