简体   繁体   English

严格模式下的对象

[英]Object in strict mode

I have an object and I need it to run the content of the page. 我有一个对象,需要它来运行页面的内容。 I need to wrap it with strict mode. 我需要用严格模式包装它。 I tried to return it to use in global scope, but it didn't solve my issue. 我试图将其返回以在全局范围内使用,但是并不能解决我的问题。

(function($) {
   "use strict";

   var MyObj = {
       // some code here.
   }

   return MyObj;

})(jQuery);

console.log(MyObj); // <= undefined

How can I access to this object from anywhere of my project? 如何从项目的任何位置访问此对象?

What you have there is an immediately-invoked function expression (IIFE) which is specifically designed to keep things separate from the external scope. 您拥有的是立即调用的函数表达式(IIFE) ,该函数表达式专门用于使事物与外部范围分开。 Since you're returning MyObj , all you have to do to make it available in the global scope is this: 由于您要返回MyObj ,因此需要做的就是使它在全局范围内可用:

var MyObj = (function($) {
    "use strict";

    var MyObj = {
        // some code here.
    }

    return MyObj;

})(jQuery);

console.log(MyObj);

The other way to do this would be to put MyObj in the global space explicitly. 执行此操作的另一种方法是将MyObj明确放置在全局空间中。 In a browser, the global object is called window , so you could, inside your IIFE, say window.MyObj = { /* some code here */ } . 在浏览器中,全局对象称为window ,因此您可以在IIFE内说window.MyObj window.MyObj = { /* some code here */ } I would discourage this approach, though, because it's not clear to the outside observer that that's happening (ie, you would have to rely on documentation). 但是,我不鼓励使用这种方法,因为外部观察者尚不清楚这种情况的发生(即,您必须依靠文档)。 The better approach is to return the objects you want to expose, and the caller can choose to put those in global space. 更好的方法是返回要公开的对象,调用者可以选择将它们放在全局空间中。

Using use strict , you can only put an Object in int the global namespace explicitly. 使用use strict ,您只能将Object显式地放入int全局名称空间中。 For example, you could use window.myObj = MyObj in your function. 例如,您可以在函数中使用window.myObj = MyObj

Another possible way to achieve your goal is by passing the global object to your function (it could be window in the browser or global in nodejs). 实现目标的另一种可能方法是将全局对象传递给函数(它可以是浏览器中的窗口,也可以是nodejs中的全局对象)。

(function($, global) {
   "use strict";
   var MyObj = {}
   global.myObj = MyObj;
})(jQuery, window);

Moreover, as Ethan suggested, since you return MyObj, you could simply assign the result of the invocation to a variable. 而且,正如Ethan所建议的那样,由于返回MyObj,因此可以简单地将调用结果分配给变量。

var myObj = (function($) {
   "use strict";
   var MyObj = {}
   return x
})(jQuery);
myObj; //now defined in the global scope

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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