Tuesday, 15 September 2015

javascript - Nested .bind not working as expected -



javascript - Nested .bind not working as expected -

unfortunately .bind has been giving me grief when creating more complex closures.

i quite interested in why .bind seems work differently 1 time nest functions.

for illustration :

function t(){ t = t.bind({}); //correctly assigns *this* t function nested_t(){ nested_t = nested_t.bind({}); // fails assign *this* nested_t homecoming nested_t; } homecoming nested_t(); } //case 1 alert(t()); // alerts whole function t instead of nested_t //case 2 aleft(t.call(t)); // alerts global object (window)

in both cases expecting behavior this:

function t(){ var nested_t = function nested_t(){ homecoming this; }; homecoming nested_t.call(nested_t); } alert(t.call(t));

if explain behavior of .bind in first (and/or) sec case much appreciated!

so, i'm not exclusively reproducing issue here (both cases homecoming global object), i'll seek , explain code see it.

function t(){ t = t.bind({}); //correctly assigns *this* t function nested_t(){ nested_t = nested_t.bind({}); // fails assign *this* nested_t homecoming this; } homecoming nested_t(); } //case 1 alert(t());

let's take step step.

first, function t() defined. then, upon call, gets overwritten clean context. however, don't see usage of context.

now, nested function (nested_t) defined. upon call, overwritten clean context. returns context had when called.

back t(). homecoming result of nested_t(), not nested_t itself. in original function call, nested_t still beingness called global context.

therefore, when run t(), returns global object.

javascript closures call bind nested-function

No comments:

Post a Comment