gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:26:51 24 4
gpt4 key购买 nike

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

关于javascript - 如何将匿名函数的返回值存储到 JavaScript 中的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48863014/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com