2014-08-28 87 views
0

爲什麼斷言失敗? isNimble不是窗口的屬性,我認爲命名函數會隱式添加爲窗口屬性,但事實並非如此。這是爲什麼?同樣,canFly也沒有添加到窗口中。Javascript函數不是窗口的屬性?

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"); 

}

+0

你是什麼意思「這些斷言失敗」?你的意思是他們檢查的條件失敗,或者你的意思是函數調用本身在某種程度上失敗了嗎? – kinakuta 2014-08-28 06:13:09

+3

這裏的命名函數只在onLoad函數的範圍內。將它移到onload函數之外,並將它放在窗口對象 – Gabe 2014-08-28 06:14:12

+0

'isNimble = function(){return true;}' – 2014-08-28 06:16:02

回答

1

其它功能內部函數聲明局部範圍,並且不成爲window對象的屬性。

只需使用typeof isNimble