gpt4 book ai didi

javascript - 导出类或对象实例差异

转载 作者:行者123 更新时间:2023-12-05 00:36:24 26 4
gpt4 key购买 nike

我很困惑,或者我可以说,我不知道导出实际上是如何工作的。
我有一个 React 应用程序,并且我有一些 protected 路由。登录时,我创建了一个 Client对象实例,通过Context传递给子组件,然后消费。
最近我看到了一种方法,示例代码直接从文件中导出对象实例,然后将其导入他们想要使用的文件中。

/** My approach **/
export default Example

/** The Object Instance approach **/
export default new Example()
对象实例的生命周期是什么?第二种方法是否有任何缺点,因为它似乎更容易?

最佳答案

如果你导出类,用

export default Example
然后模块的消费者将能够实例化他们自己的实例,并且每个实例都能够拥有自己的数据。例如
// 1.js
import TheClass from './TheClass';
const tc1 = new TheClass();
tc1.foo = 'foo';
// 2.js
import TheClass from './TheClass';
const tc2 = new TheClass();
tc2.foo = 'bar';
两个模块都可以继续使用 tc1tc2完全独立,因为它们是单独的实例。
但是如果原始模块导出一个实例而不是一个类,那么该模块的所有消费者都被迫使用同一个实例:
// 1.js
import theInstance from '...';
theInstance.foo = 'foo';
// 2.js
import theInstance from '...';
// might not be a good idea to do theInstance.foo = 'bar' here
// because that will affect 1.js as well
// and will affect any other modules that imported the instance
简而言之 - 导出类比导出实例更可重用。有时潜在的可重用性是脚本编写者认为重要的,有时则不是。 (有时,即使您最初认为它没有用,但您以后可能会遇到迫使您重新考虑的情况。)
有时你想确保脚本中只有一个实例,在这种情况下
export default new Example()
是实现它的一种方法。

关于javascript - 导出类或对象实例差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69666389/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com