gpt4 book ai didi

javascript - 一般 JavaScript 语法问题

转载 作者:行者123 更新时间:2023-12-04 02:07:09 25 4
gpt4 key购买 nike

在下面的代码中,为什么两个方法(increment 和 print)都列在 return 中?为什么不能只使用 return counter++?另外,返回 console.log 是什么意思?

function create() {
var counter = 0;
return {
increment: function() {
counter++;
},
print: function() {
console.log(counter);
}
}
}

谢谢!

最佳答案

这返回的或多或少是一个计数器,如果我们重命名最顶层的函数,它应该更有意义。

它有什么作用?让我们添加一些评论

function Counter() { // a function, nothing special here
var counter = 0; // a variable that's local to the function Counter
return { // return an object literal {}
// which has a property named 'increment'
increment: function() { // that's a function AND a closure
counter++; // and therefore still has access to the variable 'counter' inside of Counter
},
print: function() { // another function
console.log(counter); // this logs to the console in most web browser
// the console object was introduces by Firebug
// and effort is made being to standardize it
}
}
}

示例用法:

var a = Counter(); // you don't need the new keyword here sinc in this case
// there's no difference because the implicit return overwrites
// the normal constructor behavior of returning 'this'
a.increment();
a.print(); // 1
var b = Counter();
b.print(); // 0

请注意函数内部的变量counter 无法从外部访问,因此它是只读,您只能通过使用closure 来实现这种效果。 .

关于javascript - 一般 JavaScript 语法问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4532407/

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