如何向某人解释JavaScript关闭,知道它们所构成的概念(例如功能、变量等),但不了解关闭本身?
我已经在维基百科上看到了图表的例子,但不幸的是,它没有帮助。
如何向某人解释JavaScript关闭,知道它们所构成的概念(例如功能、变量等),但不了解关闭本身?
我已经在维基百科上看到了图表的例子,但不幸的是,它没有帮助。
当前回答
让我们从这里开始,正如MDN所定义的那样:关闭是指独立(自由)变量的功能(被本地使用的变量,但在关闭范围内定义)。
function init() {
var name = 'Mozilla'; // name is a local variable created by init
function displayName() { // displayName() is the inner function, a closure
alert(name); // use variable declared in the parent function
}
displayName();
}
init();
function init() {
var name = "Mozilla"; // name is a local variable created by init
function displayName() { // displayName() is the inner function, a closure
alert (name); // displayName() uses variable declared in the parent function
}
displayName();
}
init();
关闭现在考虑下面的例子:
function makeFunc() {
var name = 'Mozilla';
function displayName() {
alert(name);
}
return displayName;
}
var myFunc = makeFunc();
myFunc();
function makeAdder(x) {
return function(y) {
return x + y;
};
}
var add5 = makeAdder(5);
var add10 = makeAdder(10);
console.log(add5(2)); // 7
console.log(add10(2)); // 12
您可能想要做到这一点的情况在网上特别常见. 在前端JavaScript中写的代码的大部分是基于事件的 - 我们定义了一些行为,然后将其附加到用户发起的事件(如点击或键盘)。
例如,假设我们想添加一些按钮到一个页面,调整文本大小的一种方式是指定字体元素的字体大小在像素,然后设置页面上的其他元素的大小(如标题)使用相应的EM单位:
body {
font-family: Helvetica, Arial, sans-serif;
font-size: 12px;
}
h1 {
font-size: 1.5em;
}
h2 {
font-size: 1.2em;
}
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;
<a href="#" id="size-12">12</a>
<a href="#" id="size-14">14</a>
<a href="#" id="size-16">16</a>
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;
要了解更多关于关闭的信息,请访问MDN的链接
其他回答
这就是一个初学者围绕一个关闭的头像一个功能被关闭在一个功能的身体也被称为关闭。
关于JavaScript的定义“关闭是一种功能,加上连接到函数创建的范围” -Axel Rauschmayer博士
那么,这会是什么样子呢?这就是一个例子。
function newCounter() {
var counter = 0;
return function increment() {
counter += 1;
}
}
var counter1 = newCounter();
var counter2 = newCounter();
counter1(); // Number of events: 1
counter1(); // Number of events: 2
counter2(); // Number of events: 1
counter1(); // Number of events: 3
newCounter 通过 increment 关闭, counter 可以通过 increment 引用和访问。
对1和对2将保持自己的价值的跟踪。
简单但希望有一个清晰的观点,什么关闭是围绕所有这些伟大和先进的答案。
var foo = function() {
alert("Hello World!");
};
var bar = function(arg) {
return arg;
};
bar(foo)();
function add(value1, value2) {
function doAdd(operand1, operand2) {
return operand1 + operand2;
}
return doAdd(value1, value2);
}
var foo = add(1, 2);
// foo equals 3
function add(value1, value2) {
function doAdd() {
return value1 + value2;
}
return doAdd();
}
var foo = add(1, 2);
// foo equals 3
创建关闭 一个关闭是当一个内部函数从创建它的函数的外部可访问时创建的,这通常发生在一个外部函数返回一个内部函数时,当这种情况发生时,内部函数保持了一个参考到它创建的环境。
function add(value1) {
return function doAdd(value2) {
return value1 + value2;
};
}
var increment = add(1);
var foo = increment(2);
// foo equals 3
function increment(value2) {
return 1 + value2;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Closures</title>
<meta charset="UTF-8" />
<script>
window.addEventListener("load", function() {
window.setInterval(showMessage, 1000, "some message<br />");
});
function showMessage(message) {
document.getElementById("message").innerHTML += message;
}
</script>
</head>
<body>
<span id="message"></span>
</body>
</html>
window.addEventListener("load", function() {
var showMessage = getClosure("some message<br />");
window.setInterval(showMessage, 1000);
});
function getClosure(message) {
function showMessage() {
document.getElementById("message").innerHTML += message;
}
return showMessage;
}
模拟私人数据
function Person(name) {
this._name = name;
this.getName = function() {
return this._name;
};
}
var person = new Person("Colin");
person._name = "Tom";
// person.getName() now returns "Tom"
function Person(name) {
var _name = name;
this.getName = function() {
return _name;
};
}
var person = new Person("Colin");
person._name = "Tom";
// person._name is "Tom" but person.getName() returns "Colin"
在LOPS
<!DOCTYPE html>
<html lang="en">
<head>
<title>Closures</title>
<meta charset="UTF-8" />
<script>
window.addEventListener("load", function() {
for (var i = 1; i < 4; i++) {
var button = document.getElementById("button" + i);
button.addEventListener("click", function() {
alert("Clicked button " + i);
});
}
});
</script>
</head>
<body>
<input type="button" id="button1" value="One" />
<input type="button" id="button2" value="Two" />
<input type="button" id="button3" value="Three" />
</body>
</html>
要解决这个问题,关闭必须从实际路径变量中分开,这可以通过呼叫一个新的函数来完成,这反过来创造了一个新的参考环境,下面的例子表明如何做到这一点,路径变量转移到 getHandler() 函数, getHandler() 然后返回一个独立于原来的“为”路径的关闭。
function getHandler(i) {
return function handler() {
alert("Clicked button " + i);
};
}
window.addEventListener("load", function() {
for (var i = 1; i < 4; i++) {
var button = document.getElementById("button" + i);
button.addEventListener("click", getHandler(i));
}
});
function Person(name) {
var _name = name;
this.getName = function() {
return _name;
};
this.sayHello = function() {
alert("Hello!");
};
}
function Person(name) {
var _name = name;
this.getName = function() {
return _name;
};
}
Person.prototype.sayHello = function() {
alert("Hello!");
};
要记住的事情
也许你应该考虑一个以对象为导向的结构而不是内部功能。
var calculate = {
number: 0,
init: function (num) {
this.number = num;
},
add: function (val) {
this.number += val;
},
rem: function (val) {
this.number -= val;
}
};
并从 calculate.number 变量中阅读结果,谁需要“返回”无论如何。
//Addition
First think about scope which defines what variable you have to access to (In Javascript);
//there are two kinds of scope
Global Scope which include variable declared outside function or curly brace
let globalVariable = "foo";
一件事要记住,一旦你宣布了一个全球变量,你可以在你的代码中的任何地方使用它,即使在功能中;
包含仅在您的代码的特定部分可用的变量的本地范围:
函数范围是当您在函数中宣布变量时,您只能在函数内访问变量。
function User(){
let name = "foo";
alert(name);
}
alert(name);//error
//Block scope is when you declare a variable within a block then you can access that variable only within a block
{
let user = "foo";
alert(user);
}
alert(user);
//Uncaught ReferenceError: user is not defined at.....
//A Closure
function User(fname){
return function(lname){
return fname + " " lname;
}
}
let names = User("foo");
alert(names("bar"));
//When you create a function within a function you've created a closure, in our example above since the outer function is returned the inner function got access to outer function's scope
皮诺基奥:1883年关闭(JavaScript前一世纪)
我想这最好可以解释给一个有趣的冒险的6岁男孩......Pinocchio的冒险的一部分,在那里Pinocchio被一个过度的狗鱼吞下。
var tellStoryOfPinocchio = 函数(原始) { // 准备令人兴奋的事情发生 var pinocchioFindsMisterGeppetto; var happyEnding; // 故事开始在那里Pinocchio寻找他的“父亲” var pinocchio = { 名称:‘Pinocchio’,位置:‘在海里’,鼻子长度: 2 }; // 它是一只狗......它是一只鱼...... // 狗鱼出现,但是我
关闭是通过内部函数可以提到在其外部关闭函数中存在的变量,其母函数已经结束后。
// A function that generates a new function for adding numbers.
function addGenerator( num ) {
// Return a simple function for adding two numbers
// with the first number borrowed from the generator
return function( toAdd ) {
return num + toAdd
};
}
// addFive now contains a function that takes one argument,
// adds five to it, and returns the resulting number.
var addFive = addGenerator( 5 );
// We can see here that the result of the addFive function is 9,
// when passed an argument of 4.
alert( addFive( 4 ) == 9 );