console.error.bind...?

1,968 views
Skip to first unread message

Anthony Kerz

unread,
Dec 9, 2013, 10:07:00 PM12/9/13
to mongoo...@googlegroups.com

going thru the quick start, i see this:

db.on('error', console.error.bind(console, 'connection error:'));

i’m not familiar with that console.error.bind syntax, can someone set me straight?

regards,
tony.

Jason Crawford

unread,
Dec 9, 2013, 10:16:08 PM12/9/13
to mongoo...@googlegroups.com
The bind call is pretty fundamental to JavaScript; here's some documentation:


Bottom line:

    console.error.bind(console, 'foo')

is basically equivalent to

    function () { console.error('foo'); }

But to fully understand why, it would help to read up on how functions work in JavaScript in general, especially different patterns of function invocation. Check out that documentation link above, and/or avail yourself of a reference like Crockford's book: http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742

Good luck,
Jason

--
Blog: http://blog.jasoncrawford.org  |  Twitter: @jasoncrawford




--
Documentation - http://mongoosejs.com/
Plugins - http://plugins.mongoosejs.com/
Bug Reports - http://github.com/learnboost/mongoose
Production Examples - http://mongoosejs.tumblr.com/
StackOverflow - http://stackoverflow.com/questions/tagged/mongoose
Google Groups - https://groups.google.com/forum/?fromgroups#!forum/mongoose-orm
Twitter - https://twitter.com/mongoosejs
IRC - #mongoosejs
---
You received this message because you are subscribed to the Google Groups "Mongoose Node.JS ODM" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongoose-orm...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Anthony Kerz

unread,
Dec 9, 2013, 10:45:37 PM12/9/13
to mongoo...@googlegroups.com

thanks jason,

now that you refreshed my memory, i’ve seen that core js bind() before.

i guess since:
(a) my head was in mongoose and
(b) every time i read about bind() my brain tucks it away in the “advanced stuff i won’t be using soon” junk drawer,
it didn’t click…

i should remember it now, at least to save my self some embarrassment ;)

then let me rephrase my original question to:

can anyone very briefly explain why we need to use bind() here:

db.on('error', console.error.bind(console, 'connection error:'));

like, could we have avoided bind() with something like:

db.on('error', function(err) { console.error('connection error: %s', err); })

?

Jason Crawford

unread,
Dec 9, 2013, 11:59:29 PM12/9/13
to mongoo...@googlegroups.com
Sure, you could do that. I would probably write it that way, personally. My guess is that whoever wrote the code decided that the shorter version was better.

-Jason

Reply all
Reply to author
Forward
0 new messages