简体   繁体   English

如何在javascript中定义新的全局对象

[英]How to define a new global object in javascript

Hi It is good practice to create one unique global object that wrap the functions and properties inside this object.I look up a lot of sample code and see code like this 嗨这是一个很好的做法,创建一个唯一的全局对象,包含此对象中的函数和属性。我查找了很多示例代码,看到这样的代码

if(!myglobalObject) myglobalObject ={};

However , this code does not work ,I got an error saying ReferenceError: myglobalObject is not defined Can anyone shed some light on why I got the error? 但是,这段代码不起作用,我得到一个错误,说ReferenceError:myglobalObject没有定义任何人都可以解释为什么我得到错误?

if (typeof myglobalObject === 'undefined') var myglobalObject = {};

To avoid errors in ECMAScript 5 strict mode, you need to use var to define all variables: 为避免ECMAScript 5严格模式中的错误,您需要使用var来定义所有变量:

if (typeof myglobalObject == "undefined") {
    var myglobalObject = {};
}

The other alternative is to assign a property to the global object: 另一种方法是将属性分配给全局对象:

// The following line gets you a global object in any ECMAScript
// environment, so long as it runs in the global scope. In browsers,
// you could just use window.
var globalObj = this;
if (typeof globalObj.myglobalObject == "undefined") {
    globalObj.myglobalObject = {};
}

if (window['myglobalObject'] === undefined) window.myglobalObject = {};

如果你不想从上下文中公开你的对象,你可以像这样做:

var myglobalObject = myglobalObject || {};

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

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