2

while working through learnyounode, I found something that I would like some insight on from more experienced developers.

Consider this:

var http = require("http")

http.get(process.argv[2], (response) => {
    var collectData = []
    response.on("data", collectData.push) // does not work
    response.on("data", console.log) // this works

    // this works and is what I am using right now
    response.on("data", (data) => { 
        collectData.push(data)
    })

}).on("error", console.error)

As you can see, when a response.on event occurs, it passes the data to the console.log function but not the Array.push function.

Nicholas Kolatsis
  • 377
  • 1
  • 4
  • 8
  • It would appear that Node's `console.log` doesn't use `this` (in some environments, it does). `collectData.push` does. That's the difference. *"this works and is what I am using right now"* That's what you should be doing, that or `response.on("data", collectData.push.bind(collectData));` (since we know from the documentation that the `data` event's callback is called with a single argument). – T.J. Crowder Nov 16 '17 at 13:09
  • I don't think the duplicate is correct here. To address your question: It's a scope problem, when passing `collectData.push` as an argument, you only pass the reference to that function, without any reference to the array. That's why it doesn't work but the other example does. – kalsowerus Nov 16 '17 at 13:14
  • @kalsowerus: It's not a scope problem, and yes, the dupetarget is correct (its answers address what you're saying about passing the function without any indication of what array it should be called on). – T.J. Crowder Nov 16 '17 at 13:15

0 Answers0