一般JavaScript语法问题

djs*_*s22 2 javascript syntax

在下面的代码中,为什么返回列出了两个方法(增量和打印)?为什么你不能使用return counter++?还有,返回一个是什么意思console.log

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

谢谢!

Ivo*_*zel 5

返回的内容或多或少是一个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
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

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
Run Code Online (Sandbox Code Playgroud)

注意counter函数内部的变量不能从外部访问,因此它只是readonly,只能通过使用闭包来实现.