2015-09-22 57 views
1

我正在研究functional javascript workshop的部分申請部分。需要綁定或申請部分申請

我特別需要:

使用部分應用程序來創建,修復到CONSOLE.LOG的第一個參數的函數。

與示例輸出:

var info = logger('INFO:'); 
info('this is an info message'); 
// INFO: this is an info message 

我天真的作品,但不使用應用或綁定:

function logger(namespace) { 
    return (args) => console.log(namespace, args); 
}; 

const info = logger('INFO:'); 
info('this is an info message'); 
// INFO: this is an info message 

推薦的解決方案:

var slice = Array.prototype.slice 

function logger(namespace) { 
    return function() { 
    console.log.apply(console, [namespace].concat(slice.call(arguments))) 
    } 
} 

什麼我錯過了嗎?爲什麼需要綁定或應用?

+1

嘗試'info('這是一條信息'123'),你會看到你的解決方案只傳遞第一個參數。然而,推薦的方法是將所有這些命名空間連接起來,並通過apply將結果傳遞給'console.log'。 – raina77ow

+0

作爲應用的第一個參數,「console」的含義是什麼? –

+0

這是上下文對象(函數內部的'this')。 – JMM

回答

1

推薦的解決方案將通過所有參數(也許寫入時不考慮ES2015)。您的解決方案只會通過第一個參數。我想你正在尋找(...args) => console.log(namespace, ...args)