簡體   English   中英

這兩個 console.log 覆蓋有什么區別?

[英]What's the difference between these two console.log overrides?

這會毫無問題地覆蓋 console.log,這對我來說很有意義:

(function(c) {
  console.log = function() {
    c.apply(console, arguments);
  }
})(console.log);

這個不起作用,我不明白為什么:

(function(c) {
  console.log = function() {
    c(arguments);
  }
})(console.log);

當我調用 console.log 時,我只得到一個屬性列表。

有什么不同?

我需要在第二個中使用 arguments 構建數組才能正常工作。

如果你像這樣修改你的 function 它會起作用:

 (function(c) { console.log = function() { // c(...arguments) also works c(...Object.values(arguments)); } })(console.log); console.log('hello world')

這是因為arguments不是數組,而是類數組 object

 function func(...args) { console.log(arguments); } func(1, 2, "hello", "world")

第二個代碼示例沒有像您預期的那樣工作,因為您將arguments object 原樣傳遞給console.log function 而在第一個代碼示例中,由於使用了apply()arguments中的屬性object 作為單獨的參數傳遞。 換句話說,數組或類似數組的 object散布到不同的 arguments 中。

第一個代碼示例中的console.log調用類似於以下內容:

console.log(arg1, arg2, arg3, ...)

而在第二個中,它是:

console.log({ 0: arg1, 1: arg2, 2: arg3, ... });
(function(c) {
  console.log = function() {
    const a = Array.from(arguments);
    c(a.join(" "))
  }
})(console.log);

這行得通。

arguments是一個類對象,所以我們需要自己創建字符串。

暫無
暫無

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

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