[英]How can I access a variable declared within a wrapped function in the global scope?
I'm working on a Drupal library that uses two JS files — one internal to create a settings object and another external (a vendor library).我正在开发一个使用两个 JS 文件的 Drupal 库——一个在内部创建设置对象,另一个在外部(供应商库)。
Here's the local file that creates _settingsObject
with Drupal's required wrapper.这是使用 Drupal 所需的包装器创建
_settingsObject
的本地文件。
(function ($) {
'use strict';
Drupal.behaviors.myBehavior = {
attach: function (context, settings) {
_settingsObject = {
...
};
}
};
})(jQuery);
The only issue I'm having is that the other file is unable to see this object and I'm not able to access it in the console.我遇到的唯一问题是另一个文件无法看到这个对象,我无法在控制台中访问它。 How can I make this object available in the global scope?
如何使这个对象在全局范围内可用?
Thank you!谢谢!
You can add it to the window object.您可以将其添加到窗口对象。 Do it like this:
像这样做:
(function ($, window) {
'use strict';
window.globalVar = "My Global Var";
Drupal.behaviors.myBehavior = {
attach: function (context, settings) {
_settingsObject = {
...
};
}
};
})(jQuery, window);
The reason, as you hinted at, is due to scope.正如您所暗示的,原因在于范围。 I'm not 100% this will work because I don't know enough about the function, but it looks like what it is doing (correct me if I'm wrong) is adding
_settingsObject
to the Drupal.behaviors.myBehavior object, such that when you call it you would call Drupal.behaviors.... If this is the case, try returning the object at the end of the function.我不是 100% 这会起作用,因为我对这个函数了解得不够多,但看起来它在做什么(如果我错了,请纠正我)正在将
_settingsObject
添加到 Drupal.behaviors.myBehavior 对象,例如当您调用它时,您将调用 Drupal.behaviors.... 如果是这种情况,请尝试在函数末尾返回该对象。
(function ($) {
'use strict';
Drupal.behaviors.myBehavior = {
attach: function (context, settings) {
const _settingsObject = {
...
};
return _settingsObject;
}
};
})(jQuery);
If that is not the case, please revise your question to include more code, and what exactly you are calling in the other file and how you are calling it.如果不是这种情况,请修改您的问题以包含更多代码,以及您在另一个文件中调用的内容以及调用方式。 If you are trying to get the object called _settingsObject you need to return it and make it accessible from the namespace in global scope.
如果您尝试获取名为 _settingsObject 的对象,您需要返回它并使其可从全局范围内的命名空间访问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.