为什么我必须通过窗口访问全局变量?



我在文件中有一些JS,在页面上有一些JS。

如果我尝试通过 NucleusPreview 访问我的函数,
如果我通过窗口访问它,则找不到它。核预览,它被发现

为什么? 我是否做错了什么,或者在另一个函数中访问窗口范围内的对象时是否需要显式?

更新:我正在onReady中创建NucleusPreview,但移动了它,所以我认为窗口范围是一个红鲱鱼。 问题是,在onReady中调用它时,给了它时间来加载文件,但是当我将其移出时,我开始过早地调用它。

文件中的JS基本上是:

var NucleusPreview;
(function ($) {
NucleusPreview = function NucleusPreview(source) {
//ctor stuff
};
NucleusPreview.prototype.AdjustCaption = function AddCaption() {
//caption stuff
};
})(jQuery);

我在页面上的JS:

$('.nucleus-preview').each(function eachNucleusPreview(index, element) {
var jElement = $(element),
vidId = jElement.data('video-id'),
np = new NucleusPreview($(element)); //Uncaught RefError: NucleusPreview is not defined
_wq.push({
id: vidId,
onReady: function (video) {
np.AdjustCaption();
}
});
});

只要您提供的第一段代码首先执行,并且在加载 DOM 之前不执行任何代码(您可以将所有这些代码放在document.ready()回调中以确保这种情况(,您应该能够这样做。运行此代码片段并稍等片刻,您将看到它无需限定window即可工作。

在下面的示例中,我将所有代码放在一个document.ready()回调中(尽管代码运行不需要这样做(,以确保您不会在 DOM 准备就绪之前尝试访问$('.nucleus-preview')

此外,这样做将首先使NucleusPreview远离全球范围,这始终是一个好主意。

// Always make sure the DOM is fully loaded prior to scanning for DOM elements. 
// This can be done by placing all of your code in a "document.ready()` callback
// function as I'm doing here or by placing the code at the end of the HTML document,
// just before the close of the body (</body>).
$(function(){
// Now NucleusPreview is scoped to this function, which keeps it out of the
// global scope and that's always good, so you don't pollute the window.
var NucleusPreview;
(function ($) {
NucleusPreview = function NucleusPreview(source) {
//ctor stuff
};
NucleusPreview.prototype.AdjustCaption = function AddCaption() {
//caption stuff
};
})(jQuery);
var _wq = [];  // Added to allow code to execute
$('.nucleus-preview').each(function eachNucleusPreview(index, element) {
var jElement = $(element),
vidId = jElement.data('video-id'),
np = new NucleusPreview($(element)); // <-- Works just fine!
_wq.push({
id: vidId,
onReady: function (video) {
np.AdjustCaption();
}
});
});
});
console.log($('.nucleus-preview'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nucleus-preview"></div>
<div class="nucleus-preview"></div>
<div class="nucleus-preview"></div>

最新更新