对不起,标题很糟糕,但我想不出更好的一个.
Polymer中的ShadowDOM.js文件执行此操作:
(function(scope) {
"use strict";
var unsafeUnwrap = scope.unsafeUnwrap;
var wrap = scope.wrap;
var nonEnumDescriptor = {
enumerable: false
};
function nonEnum(obj, prop) {
Object.defineProperty(obj, prop, nonEnumDescriptor);
}
function NodeList() {
this.length = 0;
nonEnum(this, "length");
}
NodeList.prototype = {
item: function(index) {
return this[index];
}
};
nonEnum(NodeList.prototype, "item");
function wrapNodeList(list) {
if (list == null) return list;
var wrapperList = new NodeList();
for (var i = 0, length = list.length; i < length; i++) {
wrapperList[i] = wrap(list[i]);
}
wrapperList.length = length;
return wrapperList;
}
function addWrapNodeListMethod(wrapperConstructor, name) {
wrapperConstructor.prototype[name] = function() {
return wrapNodeList(unsafeUnwrap(this)[name].apply(unsafeUnwrap(this), arguments));
};
}
scope.wrappers.NodeList = NodeList;
scope.addWrapNodeListMethod = addWrapNodeListMethod;
scope.wrapNodeList = wrapNodeList;
})(window.ShadowDOMPolyfill);
Run Code Online (Sandbox Code Playgroud)
简单的问题:为什么传递参数window.ShadowDOMPolyfill?
是的,这是一个匿名函数,可以立即执行.是的,所有变量都将保留在功能范围内,避免污染.是的scope将是相同的window.ShadowDOMPolyfill.
这是我见过很多次的模式.我完全理解为什么不用变量等污染全局范围是好的.但是,为什么将window.ShadowDOMPolyfill作为第一个参数传递?据我所知,Window对象在函数内完全可用...所以上面的代码和之间有什么区别:
(function() {
"use strict";
var scope = window.ShadowDOMPolyfill;
...
})();
Run Code Online (Sandbox Code Playgroud)
...?
在参数列表中定义函数所需的参数被认为是一种很好的做法,以便完成分配给它的工作。
虽然完全有可能按照您建议的方式执行此操作,但它鼓励使用撒谎的 API,从某种意义上说,您无法查看函数签名并了解函数中的内容。
在这个特定的实例中,这两个示例在功能上是相同的,但是,想象一下有更多的参数,并且它们的用法和定义分散在函数体中。
(function(oneThing, anotherThing, aThirdThing) {
...
})(window.oneThing, window.anotherThing, window.aThirdThing);
Run Code Online (Sandbox Code Playgroud)
比
(function() {
... // with your vars somewhere inside.
})();
Run Code Online (Sandbox Code Playgroud)
在您的示例中,您必须与开发人员强制执行约定,始终将这些定义放在顶部,以保持可读性。然而,该语言已经帮助您通过参数列表强制执行这一点。
| 归档时间: |
|
| 查看次数: |
36 次 |
| 最近记录: |