i watching douglas crockford videos , gave following exercise :
write function, when passed variable, returns function if called , returns value of variable.
so wrote following function :
function funcky(o) { return function send(o){ // notice o in send return o; } } var x = funcky(3); console.log(x()); // undefined why ?? notice o in send. have been programming javascript while , still don't understand why undefined ??
crockfords solution follows :
function funcky(o) { return function send(){ return o; } } var x = funcky(3); console.log(x()); // 3 . now how come solution works , mine does't ? don't see of difference in solution , nothing wrong see. can explain please ?
this has scope of o. when write:
return function send(o){ // notice o in send return o; } the scope of o local function send. but, if write:
return function send(){ return o; } the scope of o not local function send, local scope of funcky.
so, when write function send(o){/*...*/} happening o becomes argument, , need called this: funcky()(10), want able funcky(10)().
edit:
for more information variable scope in javascript, please see this detailed answer on so.
Comments
Post a Comment