全局对象

当js解释器启动的时候,会创建一个全局对象,包含一些重要的初始属性如下

  • 全局属性,undefined,Infinity和NaN
  • 全局函数,parseInt()
  • 构造函数,Object(),RegExp()
  • 全局对象,Math和JSON

在客户端js中,window对象充当了全局对象的超级。并且有一个window属性引用自身。

function Window () {
    this.window = this;
    var window = this.window;
    ...
};
window = {
    ....
};
Window.call(window);
在Python中,可以通过多种方式实现全局对象的共享。 1. 使用模块变量:在一个模块中定义一个变量,并在其他模块中导入该变量来实现全局对象的共享。例如,我们可以在一个模块中定义一个全局变量,并在其他模块中导入该变量来使用它。 ```python # global_obj.py ws = None # other_module.py from global_obj import ws # 使用ws变量 ws.send(message) ``` 2. 使用类的类变量:可以在一个类中定义一个类变量,并通过类名来访问和修改该变量。这样可以实现在不同的文件中共享全局对象。 ```python # global_obj.py class WebSocket: ws = None @classmethod def send(cls, message): cls.ws.send(message) # other_module.py from global_obj import WebSocket # 使用WebSocket类的ws变量 WebSocket.ws.send(message) ``` 3. 使用单例模式:单例模式可以确保一个类只有一个实例,并提供一个全局访问点来访问该实例。在Python中,模块是在首次导入时创建的单例对象,因此可以在一个模块中定义一个类,并在其他地方导入该模块来使用单例对象。 ```python # singleton.py class SingletonClass: def __init__(self): # 初始化对象 pass # 创建单例对象 singleton_instance = SingletonClass() # other_module.py from singleton import singleton_instance # 使用singleton_instance对象 singleton_instance.do_something() ``` 这些方法都可以实现在不同的文件中共享全局对象。具体使用哪种方法取决于你的需求和项目结构。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值