Javascript 对象相互交叉引用
Javascript Objects cross referencing each other
我正在尝试为 router5 开发一个插件。
router5 插件是一个接受路由器实例并返回具有名称和一些方法的对象的函数。
您可以在下面找到代码的相关部分:
function myPluginFactory(store) {
// So that store can be in the closure
function myPlugin(router){
// The router will reference the store
router.setDependency({'store': store});
// The store will reference the router
store.setRouter(router);
// Public APi
return {
onTransitionStart(fromState, toState){
router.onTransitionStart(fromState, toState);
}
// ...
}
}
myPlugin.pluginName = "MY_PLUGIN";
return myPlugin;
}
class RouterStore {
router = null;
setRouter(router) {
this.router = router;
}
}
// **************** //
import routes from './routes';
import createRouter from 'router5';
const myRouterStore = new RouterStore();
const router = createRouter(routes, {});
// The .usePlugin will call the function returned by
// myPluginFactory(myRouterStore) and call it passing the router instance
router.usePlugin(myPluginFactory(myRouterStore));
所以我首先实例化我的路由器,然后我调用方法 usePlugin 来创建并将我的插件传递给路由器。
我的问题来自 myPlugin 函数的前 2 条指令。
即:
- 我创建了从路由器对象到存储对象的引用
- 创建从存储对象到路由器对象的引用
这将创建一个交叉引用。
问题:
这种交叉引用是否会在 javascript 中产生问题?我可以陷入某种循环呼叫并打破宇宙吗?
这是一个丑陋的模式,应该避免吗?
用这个模式就可以了。交叉引用用于在 js 中实现树和图形,它很常见。
但这可能会导致内存泄漏,因为 js 对象只有在没有对它们的引用时才会被垃圾回收。 (在你的例子中不太可能)
尽管在按属性进行的嵌套迭代中 ti 冷创建了一个无限循环。
模式没有问题。
垃圾收集器偶尔会从根(全局范围)开始跟踪每个引用。这意味着无法访问的循环引用将被垃圾收集。
你不应该担心这些东西。垃圾收集器的整个想法就是让你承担起这个责任。
我正在尝试为 router5 开发一个插件。
router5 插件是一个接受路由器实例并返回具有名称和一些方法的对象的函数。
您可以在下面找到代码的相关部分:
function myPluginFactory(store) {
// So that store can be in the closure
function myPlugin(router){
// The router will reference the store
router.setDependency({'store': store});
// The store will reference the router
store.setRouter(router);
// Public APi
return {
onTransitionStart(fromState, toState){
router.onTransitionStart(fromState, toState);
}
// ...
}
}
myPlugin.pluginName = "MY_PLUGIN";
return myPlugin;
}
class RouterStore {
router = null;
setRouter(router) {
this.router = router;
}
}
// **************** //
import routes from './routes';
import createRouter from 'router5';
const myRouterStore = new RouterStore();
const router = createRouter(routes, {});
// The .usePlugin will call the function returned by
// myPluginFactory(myRouterStore) and call it passing the router instance
router.usePlugin(myPluginFactory(myRouterStore));
所以我首先实例化我的路由器,然后我调用方法 usePlugin 来创建并将我的插件传递给路由器。
我的问题来自 myPlugin 函数的前 2 条指令。
即:
- 我创建了从路由器对象到存储对象的引用
- 创建从存储对象到路由器对象的引用
这将创建一个交叉引用。
问题:
这种交叉引用是否会在 javascript 中产生问题?我可以陷入某种循环呼叫并打破宇宙吗?
这是一个丑陋的模式,应该避免吗?
用这个模式就可以了。交叉引用用于在 js 中实现树和图形,它很常见。 但这可能会导致内存泄漏,因为 js 对象只有在没有对它们的引用时才会被垃圾回收。 (在你的例子中不太可能) 尽管在按属性进行的嵌套迭代中 ti 冷创建了一个无限循环。
模式没有问题。
垃圾收集器偶尔会从根(全局范围)开始跟踪每个引用。这意味着无法访问的循环引用将被垃圾收集。
你不应该担心这些东西。垃圾收集器的整个想法就是让你承担起这个责任。