【发布时间】:2014-04-07 01:27:21
【问题描述】:
从下面的例子中,我想我理解了所有的代码,除了我无法理解为什么需要 this.assert 和 this.test? 没有它们,这段代码就不能忍受吗?
这是来自 javascript ninja 的秘密一书
<script>
(function() {
var results;
this.assert = function assert(value,desc) {
var li = document.createElement("li");
li.className = value ? "pass" : "fail";
li.appendChild(document.createTextNode(desc));
results.appendChild(li);
if (!value) {
li.parentNode.parentNode.className = "fail";
}
return li;
};
this.test = function test(name,fn) {
console.log("JOT");
results = document.getElementById("results");
console.log("this is" , results)
results = assert(true, name).appendChild(
document.createElement("ul"));
fn();
};
})();
window.onload = function() {
console.log("before");
test("A test.", function() {
console.log("after a test");
assert(true, "First assertion completed");
console.log("after assert1");
assert(true, "Second assertion completed");
console.log("after assert2");
assert(true, "Third assertion completed");
console.log("after assert3");
});
test("Another test.", function() {
assert(true, "First test completed");
assert(true, "Second test completed");
assert(false, "Third test fail");
});
test("Another test.", function() {
assert(true, "First test completed");
assert(true, "Second test completed");
assert(true, "Third test completed");
});
};
</script>
【问题讨论】:
-
“为什么需要它们”是什么意思?如果它们不存在,您将无法在 window.onload 方法中调用它们。
-
这里不建议使用命名函数表达式。 IE have issues with them 的某些版本以及名称应该仅在函数本身中可用。鉴于这些名称并未在函数本身中使用,因此拥有它们似乎并不明智。我也不认为这是创建全局对象属性的明智方法。在我看来,它应该在严格模式下失败。
-
使用命名函数表达式是个好主意。它有助于调试。
-
考虑到 IE 和严格模式的问题,并且可以用函数声明替换它们,我不明白这一点。请考虑:
(function(global){var result; function assert(){...}; global.assert = assert; ...}(this));。适用于任何地方(包括严格模式),名称可在函数内部用于调试,它们被显式添加为全局变量,并保留 result 的闭包。那里赢了很多。 :-)
标签: javascript ninja