Domanda

From below example, I think I understand all the code except I cannot get my head around why this.assert and this.test is needed?? Can't this code stand without them?

This is from the book Secrets of the 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>
È stato utile?

Soluzione

this in the top function refers to the global object, because it's called neither as a constructor nor as a method. In a web browser, the global object is window.

Anyway, assigning a property to the global object allows you to reference it as a global variable. Later on in the code, assert and test are available in the onload function.

So why not just say window.assert = ...? One reason is that the construction in the code sample is slightly more portable, in case you need to run it in a JavaScript environment where the global object isn't window.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top