这段代码有什么作用?
g = "undefined" !== typeof exports ? exports : k.Backbone = {};
这段代码有什么作用?
g = "undefined" !== typeof exports ? exports : k.Backbone = {};
它是以下的简写:
if("undefined" !== typeof exports)
g = exports;
}else{
g = k.Backbone = {};
}
被:?
称为三元运算符
如果我这样写,也许它更具可读性:
g = ("undefined" !== typeof exports) // If
? exports // Then
: k.Backbone = {}; // Else
它将 Backbone 定义为 CommonJS 模块,因此可以在 Node.js 等 CommonJS 兼容环境中加载。
您正在查看缩小的源代码。这是未缩小的样子:
var Backbone;
if (typeof exports !== 'undefined') {
Backbone = exports;
} else {
Backbone = root.Backbone = {};
}
该变量exports
是 CommonJS 模块定义的返回对象。在 CommonJS 环境中,Backbone
变量设置为该值,因此Backbone
从模块中导出。
If exports
is undefined, it is assumed that the code is in the browser environment, and Backbone
should be exported a property on the root
object, which refers to window
, the browser´s global scope.