当前位置: 动力学知识库 > 问答 > 编程问答 >

ecmascript 5 - Having trouble passing in a dependent object to a Javascript Module

问题描述:

I have the following code:

var myModule = (function($) {

// Insert code here

} (jQuery || Zepto));

If I don't have jQuery referenced on the page, the script errors out saying that jQuery is undefined. There's many times in code where I'll write var foo = missingObj || fallbackObj; and it works fine.

I'm trying to figure out a) why it doesn't work in this context and b) what an alternative would be since I would like to use this projects that use either framework.

网友答案:

var foo = missingObj || fallbackObj;

only works if missingObj is not undeclared. For example. this happens when missingObj is an argument whose value is undefined (this is the most common use case for x = y || default)

The code your looking for is

} (window.jQuery || window.Zepto));

So basically the reason it doesn't work is because your confusing objects who have a value undefined and objects which are undeclared.

Accessing jQuery is accessing an undeclared value, which doesn't work. Accessing window.jQuery is accessing an undefined value, which does work.

For example

function jQuery(options) {
  options = options || {};
  ...
}

Works because options is undefined rather then undeclared

分享给朋友:
您可能感兴趣的文章:
随机阅读: