闭包和普通函数的区别

问题描述 投票:0回答:2

我在浏览 Mozilla 中的闭包定义时发现了这个例子 -

function makeSizer(size) {
  return function () {
    document.body.style.fontSize = `${size}px`;
  };
}

const size12 = makeSizer(12);
const size14 = makeSizer(14);
const size16 = makeSizer(16);

我还是不明白的是,如果我想增加字体,我仍然可以这样做-

function makeSizer(size) {
  document.body.style.fontSize = `${size}px`;
}

const size12 = makeSizer(12);
const size14 = makeSizer(14);
const size16 = makeSizer(16);

这里闭包的概念是什么?为什么要有额外的内部功能? 请纠正我的理解。

javascript closures lexical-closures
2个回答
1
投票

不同之处在于,在第一个代码块中,

makeSizer
创建并返回一个尚未调用的函数。 如果你调用它,它会将给定的
size
应用于元素。 (如果你不调用它,它就不会。)相比之下,你的重写提供了直接使用的大小并立即完成工作。

我觉得如果用经典的例子可能会更清楚,更简单一些(见评论):

function makeAdder(addend) {
    return function (value) {
        return value + addend;
    };
}

// Let's make a function that will add 6 to whatever value we give it
const add6 = makeAdder(6);

// At this point, we haven't *called* the adder, we've just created it

// Let's call it:
console.log(add6(7));   // 13
console.log(add6(2));   // 8
console.log(add6(36));  // 42

这个相关问题的答案也可能有用:JavaScript 闭包如何工作?


1
投票

函数关闭

size
变量,因此当您调用返回的函数时,
size
的值将与您为
makeSizer
函数提供的值相同。如果不关闭,
makeSizer
返回 undefined 并且不能被重用。

function makeSizerClosure(size) {
    return function () {
        document.body.style.fontSize = `${size}px`
    }
}

const size12c = makeSizerClosure(12)
const size14c = makeSizerClosure(14)
const size16c = makeSizerClosure(16)

size12c() // size12c sets fontSize to 12, cause it knows the size value as it's closured

function makeSizer(size) {
    document.body.style.fontSize = `${size}px`
}

const size12 = makeSizer(12)
const size14 = makeSizer(14)
const size16 = makeSizer(16)

// you can't even run it cause it's undefined
size12() // error: size12 is not a function
© www.soinside.com 2019 - 2024. All rights reserved.