Javascript函数是';这不是窗户的特性吗?
为什么资产不成立?isNimble不是window的一个属性,我原以为命名函数会被隐式添加为window属性,但事实并非如此。为什么呢?同样,canFly也没有添加到窗口中 HTML:Javascript函数是';这不是窗户的特性吗?,javascript,Javascript,为什么资产不成立?isNimble不是window的一个属性,我原以为命名函数会被隐式添加为window属性,但事实并非如此。为什么呢?同样,canFly也没有添加到窗口中 HTML: <head lang="en"> <meta charset="UTF-8"> <title>test</title> <script src="test.js"></script> <style> #results li
<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>
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");
}其他函数中的函数声明是局部范围的,不会成为
窗口
对象的属性
只需使用isNimble的
类型
你所说的“这些断言失败”是什么意思?你是说他们正在检查的条件失败了,还是说函数调用本身以某种方式失败了?这里的命名函数只在onLoad函数的范围内。将它移到onload函数之外,它将被放到窗口对象isNimble=function(){return true;}