如何向某人解释JavaScript关闭,知道它们所构成的概念(例如功能、变量等),但不了解关闭本身?
我已经在维基百科上看到了图表的例子,但不幸的是,它没有帮助。
如何向某人解释JavaScript关闭,知道它们所构成的概念(例如功能、变量等),但不了解关闭本身?
我已经在维基百科上看到了图表的例子,但不幸的是,它没有帮助。
当前回答
也许你应该考虑一个以对象为导向的结构而不是内部功能。
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
其他回答
函数和函数的外部范围(语法环境)的参考
函数 汽车(制造商,模型,年,颜色) { 返回 { 到String() { 返回 `${ 制造商} ${ 模型} (${ 年}, ${ 颜色})` } } 组车 = 新车(‘Aston Martin’,‘V8 Vantage’,‘2012’,‘Quantum Silver’) console.log(car.toString())
事件导向的编程
在下面的例子中,所有实施细节都隐藏在即时执行的函数表达式内。 函数标记和 toString 接近私人状态和函数他们需要完成工作。 关闭已使我们能够模块化和包容我们的代码。
例子1
这个例子表明,本地变量在关闭中没有复制:关闭保持了对原始变量的参考。
左边
这里是一个简单的实时场景,只需阅读它,你会明白我们如何在这里使用关闭(看看座位数量如何变化)。
此前所解释的所有其他例子,也很好地理解这个概念。
function movieBooking(movieName) {
var bookedSeatCount = 0;
return function(name) {
++bookedSeatCount ;
alert( name + " - " + movieName + ", Seat - " + bookedSeatCount )
};
};
var MI1 = movieBooking("Mission Impossible 1 ");
var MI2 = movieBooking("Mission Impossible 2 ");
MI1("Mayur");
// alert
// Mayur - Mission Impossible 1, Seat - 1
MI1("Raju");
// alert
// Raju - Mission Impossible 1, Seat - 2
MI2("Priyanka");
// alert
// Raja - Mission Impossible 2, Seat - 1
function sing(person) {
var firstPart = "There was " + person + " who swallowed ";
var fly = function() {
var creature = "a fly";
var result = "Perhaps she'll die";
alert(firstPart + creature + "\n" + result);
};
var spider = function() {
var creature = "a spider";
var result = "that wiggled and jiggled and tickled inside her";
alert(firstPart + creature + "\n" + result);
};
var bird = function() {
var creature = "a bird";
var result = "How absurd!";
alert(firstPart + creature + "\n" + result);
};
var cat = function() {
var creature = "a cat";
var result = "Imagine That!";
alert(firstPart + creature + "\n" + result);
};
fly();
spider();
bird();
cat();
}
var person="an old lady";
sing(person);
指示
我没有时间去购物,所以函数需要知道我们在冰箱里有什么来做出决定。 每个成分都有不同的烹饪时间,我们希望所有的东西都被机器人同时加热。 我们需要提供函数与我们喜欢的数据,函数可以“说话”到冰箱,函数可以控制机器人。
function cookMeal() { /* STUFF INSIDE THE FUNCTION */ }
function sing(person) { /* STUFF INSIDE THE FUNCTION */ }
因此,这个功能可能与歌曲有关系,可能需要一些关于一个人的数据。
现在,在函数歌(),接近代码的结尾是线
var person="an old lady";
全球变量:人是一个全球变量,这意味着如果你将其值从“老太太”变成“年轻人”,这个人将继续是年轻人,直到你决定再次改变它,而代码中的任何其他功能可以看到它是一个年轻人。
sing(person);
这条线叫这个功能,就好像它叫一个狗。
关闭后,线路来了。
fly();
spider();
bird();
cat();
答案:这个答案是写的,当问题是:
正如老阿尔伯特所说:“如果你不能向一个六岁的人解释,你真的不明白自己。 好吧,我试图向一个27岁的朋友解释JS的关闭,并且完全失败了。
一时一刻:
有一位公主......
function princess() {
她在一个充满冒险的奇妙世界中生活,她遇到了她的魅力王子,围绕着一个独角兽的世界,战斗的龙,遇到了谈话的动物,以及许多其他幻想的东西。
var adventures = [];
function princeCharming() { /* ... */ }
var unicorn = { /* ... */ },
dragons = [ /* ... */ ],
squirrel = "Hello!";
/* ... */
return {
她经常会告诉他们她作为公主的最新惊人的冒险。
story: function() {
return adventures[adventures.length - 1];
}
};
}
但是,他们只会看到一个小女孩。
var littleGirl = princess();
关于魔法和幻想的故事。
littleGirl.story();
即使成年人知道真正的公主,他们永远不会相信单身或龙,因为他们永远不会看到它们。
这是一个真正的公主,里面有一个小女孩。
因为所有这些外部变量,由一个经文所指的函数,实际上是其经文所关闭的函数链中的本地变量(全球变量可以假设是某种根函数的本地变量),并且每个函数的单一执行都会产生其本地变量的新例子,因此,每个函数的执行都会返回(或以其他方式转换)。
此外,必须明白,JavaScript中的本地变量不是在滑板框中创建的,而是在滑板上,只有当没有人提到它们时才会被摧毁。当一个函数返回时,其本地变量的参考会减少,但如果在当前执行期间,它们成为关闭的一部分,并且仍然被其经文所定义的函数所提到。
一个例子:
function foo (initValue) {
//This variable is not destroyed when the foo function exits.
//It is 'captured' by the two nested functions returned below.
var value = initValue;
//Note that the two returned functions are created right now.
//If the foo function is called again, it will return
//new functions referencing a different 'value' variable.
return {
getValue: function () { return value; },
setValue: function (newValue) { value = newValue; }
}
}
function bar () {
//foo sets its local variable 'value' to 5 and returns an object with
//two functions still referencing that local variable
var obj = foo(5);
//Extracting functions just to show that no 'this' is involved here
var getValue = obj.getValue;
var setValue = obj.setValue;
alert(getValue()); //Displays 5
setValue(10);
alert(getValue()); //Displays 10
//At this point getValue and setValue functions are destroyed
//(in reality they are destroyed at the next iteration of the garbage collector).
//The local variable 'value' in the foo is no longer referenced by
//anything and is destroyed too.
}
bar();