scope - Can't access a parent's variable from a function in Javascript -


i have 2 functions. call 1 other , try access variable in scope of both function's parent. works fine seen in following javascript code:

var value = "a";  function func1() {   console.log(this.value);   func2(); }  function func2() {   console.log(value); } 

question 1: why value undefined in func2 when wrapping in require.js this?

question 2: why have use this.value in func1?

you can have @ https://plnkr.co/edit/k7tsoypqkybqeoqsegqp?p=preview see var value accessed func2.

i found solution you: add setvalue problem.js:

function setvalue(val) {   value = val; } 

and make public:

return {func1: func1, setvalue:setvalue}; 

and initialize.js call it:

problem.setvalue("d"); 

now each function in problem (func1, func2) can use variable. see in updated link.

it depends on scope of line var value. when put js in html, scope window, inside func1.

func 2 should work well, scope window well, doesn't work in linked example, because there it's not loaded window directly.


Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -