简体   繁体   中英

binding an object to the global scope

I have the following code:

var myVar = (function (window) {    

    myobj = {};

    myobj.boo = function() {
        alert('hi');
    };

    window.myVar = myobj;

})(window);

myVar.boo();

Why don't I get back the alert when I call myVar.boo() ? I've created an anonymous self-executing function and fed in the window object. Inside that I have another object with a method assigned to it. I then assign the global myVar variable to this obj. This should provide an alias to the my myobj object. However when I call the function I get an Cannot call method 'boo' of undefined error

You should either remove the first assignment

var myVar =

as you are replacing myVar value to the return of a function that doesn't return anything,

or more likely return myVar from your function, instead of assigning from inside the closure:

var myVar = (function() {
  var myobj = {};

  myobj.boo = function() {
      alert('hi');
  };

  return myobj;
})();

You are defining myVar with an undefined value here. When you are initializing it its calling the anonymous function. And stores the returned value. But the function does not return anything. So nothing is assigned to myVar . Even though you added window.myVar = myobj , it gets overrided when the function is finished.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM