javascript - Function assignment doesn't work -
i'm new node.js. have searched forum couldn't find similar question. here problem encountered. following code runs fine.
process.stdout.write("hello world!\n");
but following code:
var myprint = process.stdout.write; myprint("hello world");
will generate following error:
typeerror: cannot read property 'defaultencoding' of undefined
any suggestions? thank much.
probably, write()
method needs called correct object reference write()
method knows stream writing to. there multiple ways work around this. here's 1 way:
var myprint = process.stdout.write.bind(process.stdout); myprint("hello world");
see .bind()
on mdn more info.
for future reference, when do:
var myprint = process.stdout.write;
myprint
contains reference write
method , method called no object reference. means this
pointer inside write()
method not point @ stdout stream when call process.stdout.write()
. if method needs it's instance data (which methods do), creates problem. can "bind" object reference new temporary function using .bind()
allows assign variable , use directly attempting do.
Comments
Post a Comment