簡體   English   中英

一般JavaScript語法問題

[英]General JavaScript Syntax Question

在下面的代碼中,為什么返回列出了兩個方法(增量和打印)? 為什么你不能只使用return counter++ 另外,返回console.log是什么意思?

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

謝謝!

返回的內容或多或少是一個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不能從外部訪問,因此它只是readonly ,只能通過使用閉包來實現。

此代碼返回包含兩個方法的對象。

它使用稱為對象文字的功能:

var sampleObject = { someProperty: 3, otherProperty: "Hi there!" };

在這種情況下,屬性是函數文字。

create函數返回一個包含兩個方法的對象 - incrementprint

每次調用create函數時,都會返回一個新對象。 這意味着您可以同時擁有多個“計數器”。

var counter1 = create();
var counter2 = create();

counter1.increment();
counter1.print(); // prints 1

counter2.print(); // prints 0

順便說一句, create函數的局部變量counter通過閉包綁定到incrementprint方法。 閱讀有關閉包的信息: http//jibbering.com/faq/notes/closures/

您建議的代碼:

function create() {
  var counter = 0;
  return counter++;
}

會產生不同的影響。 那將返回0,然后遞增counter (這將超出范圍)。

實際代碼返回一個對象(使用對象文字創建,如SLaks所述)。 該對象有兩種方法, incrementprint 遞增方法遞增counter (它不返回它)。 print使用console.log打印它。

這樣做的原因是counter被關閉到對象文字的兩個方法中。 這大致意味着它保持活着,並被添加到這些方法的范圍中。 閉包是JavaScript的常用和重要特性。

跟隨返回時的增量運算符++基本上是追溯性的。 因此,如果您的變量值為5並且您按照++返回它,則返回5。

console.log()通常用於調試事物。 它在這種情況下將計數器的值輸出到控制台。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM