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

时间:2017-07-26 19:30:46

标签: javascript scope

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

如果我尝试通过NucleusPreview访问我的功能,则无法找到它 如果我通过window.NucleusPreview访问它,则会找到它

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

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

该文件中的JS基本上是:

<tbody id="results">

页面上的我的JS:

<tbody>

1 个答案:

答案 0 :(得分:0)

只要您提供的第一段代码首先执行,并且在加载DOM之前没有执行任何代码(您可以将所有代码放在document.ready()回调中以确保这是case),你应该可以。运行此代码段并稍等片刻,您将看到它在没有符合条件window的情况下有效。

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

此外,这样做会使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>