如何将匿名函数的返回值存储到JavaScript中的变量?

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

我对 JavaScript 非常陌生,所以请多多包涵。 这是我的代码片段:

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

然而,在执行时,我预计 course1.updateViews 的值为 1。相反,我在控制台中显示了整个函数,如下所示:

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

我敢肯定这是初学者的错误。那么有人可以纠正我吗?

So can anyone please Correct me on this?

您需要使用()

调用函数
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());

因为在 Course 对象中,您将 this.updateViews 声明为函数。 如果你想获得函数的 return 值,你需要通过调用来调用它:

console.log(course1.updateViews());

如果您想 updateViews 是静态属性,您可以更改声明方式:

function Course(title, instructor, views){

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

}