Was*_*and 0 javascript closures
我正在阅读关于Mozilla开发者网站上的闭包的解释,并且我正在苦苦挣扎.请查看Mozilla网站上的以下代码.我有点理解它是如何工作的,但我认为我的评论下面的代码也应该有效.如果点击18和20,为什么它不起作用?
/* mozilla dev code */
function makeSizer(size) {
return function() {
document.body.style.fontSize = size + 'px';
};
}
var size12 = makeSizer(12);
var size14 = makeSizer(14);
var size16 = makeSizer(16);
document.getElementById('size-12').onclick = size12;
document.getElementById('size-14').onclick = size14;
document.getElementById('size-16').onclick = size16;
/* end of mozilla dev example */
/* my code starts */
/* see - no inner function below */
function makeS(size) {
document.body.style.fontSize = size + 'px'
}
/* Let's see if that works */
var size18 = makeS(18);
document.getElementById('size-18').onclick = size18;
/* What about that? */
document.getElementById('size-20').onclick = makeS(20);
Run Code Online (Sandbox Code Playgroud)
为什么
CodePen:http://codepen.io/wasteland/pen/qqoooW
makeS(18) 立即调用该函数并更改大小.onclick在这种情况下undefined,您为事件分配的内容实际上是,因为这是调用时函数返回的内容,因为它没有显式返回.
function makeS(size) {
document.body.style.fontSize = size + 'px'
}
console.log("font size before calling makeS:", document.body.style.fontSize); //it's actually an empty string, hence why it doesn't show up in the output
var size18 = makeS(18);
console.log("font size after calling makeS:", document.body.style.fontSize);
console.log("what is size18?", typeof size18);Run Code Online (Sandbox Code Playgroud)
相比之下,makeSizer(18)将创建一个新的函数,在调用时,将改变大小.
function makeSizer(size) {
return function() {
document.body.style.fontSize = size + 'px';
};
}
console.log("font size before calling makeSizer:", document.body.style.fontSize); //it's actually an empty string, hence why it doesn't show up in the output
var size18Function = makeSizer(18);
console.log("font size after calling makeSizer:", document.body.style.fontSize); //it's still an empty string
console.log("what is size18Function?", typeof size18Function);
//let's call it now
size18Function();
console.log("font size after calling size18Function:", document.body.style.fontSize); //it's now changedRun Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
110 次 |
| 最近记录: |