gpt4 book ai didi

JavaScript - 闭包

转载 作者:行者123 更新时间:2023-11-28 11:15:33 27 4
gpt4 key购买 nike

我正在 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);

为什么

代码笔: http://codepen.io/wasteland/pen/qqoooW

最佳答案

makeS(18) 立即调用该函数并更改大小。在这种情况下,您分配给 onclick 事件的内容实际上是未定义,因为这就是该函数在调用时返回的内容,因为它没有显式返回。

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

相比之下,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 changed

关于JavaScript - 闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40984281/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com