JavaScript YUI3 using global variables?

2019-05-17 02:36发布

问题:

I can't work out how to update a global variable from within YUI3.

Consider the following code:

window.myVariable = 'data-one';
var yuiWrap = YUI().use('node',function(Y) {
  console.log(window.myVariable); // 'data-one'
  window.myVariable = 'data-two';
  console.log(window.myVariable); // 'data-two'
});
console.log(window.myVariable); // 'data-one'

Can anyone explain this to me? It's causing me a lot of trouble. Why can window.myVariable be accessed but not properly updated from within a YUI3 block?

I think it might have something to do with Closures but I don't understand why Closures should apply to the global "window" object.

Help?

回答1:

The callback is not fired immediately but after something happened:

Attaches one or more modules to the YUI instance. When this is executed, the requirements are analyzed, and one of several things can happen:

  • All requirements are available on the page -- The modules are attached to the instance. If supplied, the use callback is executed synchronously.
  • Modules are missing, the Get utility is not available OR the 'bootstrap' config is false -- A warning is issued about the missing modules and all available modules are attached.
  • Modules are missing, the Loader is not available but the Get utility is and boostrap is not false -- The loader is bootstrapped before doing the following....
  • Modules are missing and the Loader is available -- The loader expands the dependency tree and fetches missing modules. When the loader is finshed the callback supplied to use is executed asynchronously.