Rick
Rick

Reputation: 545

Javascript function isn't a property of window?

Why do the asserts fail? isNimble is not a property of window and I thought the named function would have been implicitly added as a window property, but it wasn't. Why is that? Likewise, canFly wasn't added to window either.

HTML:

<head lang="en">
<meta charset="UTF-8">
<title>test</title>
<script src="test.js"></script>
<style>
    #results li.pass { color: green; }
    #results li.fail { color: red; }
</style>
</head>
<body>
<ul id="results"></ul>
</body>

JS:

window.onload = function () {
function assert(value, desc) {
    var li = document.createElement("li");
    li.className = value ? "pass" : "fail";
    li.appendChild(document.createTextNode(desc));
    document.getElementById("results").appendChild(li);
}

function isNimble() {
    return true;
}

assert(typeof window.isNimble === "function", "isNimble() defined");
assert(isNimble.name === "isNimble", "isNimble() has a name");
var canFly = function () {
    return true;
};
assert(typeof window.canFly === "function", "canFly() defined");
assert(canFly.name === "", "canFly() has no name");
window.isDeadly = function () {
    return true;
};
assert(typeof window.isDeadly === "function", "isDeadly() defined");
function outer() {
    assert(typeof inner === "function", "inner() in scope before declaration");

    function inner() {
    }

    assert(typeof inner === "function", "inner() in scope after declaration");
    assert(window.inner === undefined, "inner() not in global scope");
}

outer();
assert(window.inner === undefined, "inner() still not in global scope");
window.wieldsSword = function swingsSword() {
    return true;
};
assert(window.wieldsSword.name === 'swingsSword', "wieldSword's real name is swingsSword");

}

Upvotes: 0

Views: 457

Answers (1)

Quentin
Quentin

Reputation: 944564

Function declarations inside other functions are locally scoped and do not become properties of the window object.

Just use typeof isNimble.

Upvotes: 1

Related Questions