简体   繁体   中英

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?

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()); 

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;

}

Functions can be assigned to variables in JavaScript, such that all function declarations are essentally:

var functionName = function () {....}

You call the function as:

functionName();

Functions can also be assigned to values in objects, so your assignment above is the same thing.

this.updateViews = function () {...}

It acts a lot like an object member function in various OO languages, you can call it as:

course1.updateViews();

Further enhancing this illusion, all of the variables accessible to the function where it is declared remain available. Furthermore, references to this in updateViews() refer to the parent object. Thus, views is incremented with each call... it returns {1,2,3,4,5,...} not always 2.

I hope this helps a bit, JS can be frustrating to learn, but the first class function thing is actually pretty cool.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM