私はこの本「Javascript忍者の秘密」を読んでいます。ここでは、ほとんどのコードがカスタムアサーションを使用して示されています。コードは次のとおりです。
(function () {
var queue = [],
paused = false,
results;
this.test = function test(name, fn) {
queue.push(function () {
results = document.getElementById("results");
results = assert(true, name).appendChild(
document.createElement("ul"));
fn();
});
runTest();
};
this.pause = function () {
paused = true;
};
this.resume = function () {
paused = false;
setTimeout(runTest, 1);
};
function runTest() {
if (!paused && queue.length) {
queue.shift()();
if (!paused) {
resume();
}
}
}
this.assert = function assert(value, desc) {
var li = document.createElement("li");
li.className = value ? "pass" : "fail";
li.appendChild(document.createTextNode(desc));
if (results === undefined) results = document.getElementById("results");
results.appendChild(li);
if (!value) li.parentNode.parentNode.className = "fail";
return li;
};
})();
ご覧のとおり、自己呼び出し関数です。
私はそれで遊んでいます、そして私がちょうど理解できない何かが、同じタグの間で、私がこれをする理由です:
<script type="text/javascript">
... previously shown code ...
window.onload = function(){
assert(true, "this works");
};
</script>
そして、もう一度、このようにアサートを実行すると、次のようになります。
<script type="text/javascript">
... previously shown code ...
assert(true, "this does not work");
</script>
window.onloadイベントを使用せずにアサーションを実行しようとすると、アサーションメソッドの「results.appendChild(li)」行に「UncaughtTypeError:Cannot callmethod'appendChild'tonull」というエラーが表示されます。
手伝ってくれてどうもありがとう。