我理解闭包定义为:
[A] stack-frame which is not deallocated when the function returns. (as if a 'stack-frame' were malloc'ed instead of being on the stack!)
但我不明白这个答案如何适合 JavaScript 的存储机制。解释器如何跟踪这些值?浏览器的存储机制是不是像Heap和Stack一样分段的?
这个问题的答案:How do JavaScript closures work?解释说:
[A] function reference also has a secret reference to the closure
这个神秘的“ secret 引用”背后的底层机制是什么?
编辑 许多人说这取决于实现,因此为了简单起见,请在特定实现的上下文中提供解释。
最佳答案
这是slebetman's answer的一部分问题javascript can't access private properties这很好地回答了你的问题。
The Stack:
A scope is related to the stack frame (in Computer Science it's called the "activation record" but most developers familiar with C or assembly know it better as stack frame). A scope is to a stack frame what a class is to an object. By that I mean that where an object is an instance of a class, a stack frame is an instance of scope.
Let's use a made-up language as an example. In this language, like in javascript, functions define scope. Lets take a look at an example code:
var global_var function b { var bb } function a { var aa b(); }When we read the code above, we say that the variable
aais in scope in functionaand the variablebbis in scope in functionb. Note that we don't call this thing private variables. Because the opposite of private variables are public variables and both refer to properties bound to objects. Instead we callaaandbblocal variables. The opposite of local variables are global variables (not public variables).Now, let's see what happens when we call
a:
a()gets called, create a new stack frame. Allocate space for local variables on the stack:The stack: ┌────────┐ │ var aa │ <── a's stack frame ╞════════╡ ┆ ┆ <── caller's stack frame
a()callsb(), create a new stack frame. Allocate space for local variables on the stack:The stack: ┌────────┐ │ var bb │ <── b's stack frame ╞════════╡ │ var aa │ ╞════════╡ ┆ ┆In most programming languages, and this includes javascript, a function only has access to its own stack frame. Thus
a()cannot access local variables inb()and neither can any other function or code in global scope access variables ina(). The only exception are variables in global scope. From an implementation point of view this is achieved by allocating global variables in an area of memory that does not belong to the stack. This is generally called the heap. So to complete the picture the memory at this point looks like this:The stack: The heap: ┌────────┐ ┌────────────┐ │ var bb │ │ global_var │ ╞════════╡ │ │ │ var aa │ └────────────┘ ╞════════╡ ┆ ┆(as a side note, you can also allocate variables on the heap inside functions using malloc() or new)
Now
b()completes and returns, it's stack frame is removed from the stack:The stack: The heap: ┌────────┐ ┌────────────┐ │ var aa │ │ global_var │ ╞════════╡ │ │ ┆ ┆ └────────────┘and when
a()completes the same happens to its stack frame. This is how local variables gets allocated and freed automatically - via pushing and popping objects off the stack.Closures:
A closure is a more advanced stack frame. But whereas normal stack frames gets deleted once a function returns, a language with closures will merely unlink the stack frame (or just the objects it contains) from the stack while keeping a reference to the stack frame for as long as it's required.
Now let's look at an example code of a language with closures:
function b { var bb return function { var cc } } function a { var aa return b() }Now let's see what happens if we do this:
var c = a()First function
a()is called which in turn callsb(). Stack frames are created and pushed onto the stack:The stack: ┌────────┐ │ var bb │ ╞════════╡ │ var aa │ ╞════════╡ │ var c │ ┆ ┆Function
b()returns, so it's stack frame is popped off the stack. But, functionb()returns an anonymous function which capturesbbin a closure. So we pop off the stack frame but don't delete it from memory (until all references to it has been completely garbage collected):The stack: somewhere in RAM: ┌────────┐ ┌╶╶╶╶╶╶╶╶╶┐ │ var aa │ ┆ var bb ┆ ╞════════╡ └╶╶╶╶╶╶╶╶╶┘ │ var c │ ┆ ┆
a()now returns the function toc. So the stack frame of the call tob()gets linked to the variablec. Note that it's the stack frame that gets linked, not the scope. It's kind of like if you create objects from a class it's the objects that gets assigned to variables, not the class:The stack: somewhere in RAM: ┌────────┐ ┌╶╶╶╶╶╶╶╶╶┐ │ var c╶╶├╶╶╶╶╶╶╶╶╶╶╶┆ var bb ┆ ╞════════╡ └╶╶╶╶╶╶╶╶╶┘ ┆ ┆Also note that since we haven't actually called the function
c(), the variableccis not yet allocated anywhere in memory. It's currently only a scope, not yet a stack frame until we callc().Now what happens when we call
c()? A stack frame forc()is created as normal. But this time there is a difference:The stack: ┌────────┬──────────┐ │ var cc var bb │ <──── attached closure ╞════════╤──────────┘ │ var c │ ┆ ┆The stack frame of
b()is attached to the stack frame ofc(). So from the point of view of functionc()it's stack also contains all the variables that were created when functionb()was called (Note again, not the variables in function b() but the variables created when function b() was called - in other words, not the scope of b() but the stack frame created when calling b(). The implication is that there is only one possible function b() but many calls to b() creating many stack frames).But the rules of local and global variables still applies. All variables in
b()become local variables toc()and nothing else. The function that calledc()has no access to them.What this means is that when you redefine
cin the caller's scope like this:var c = function {/* new function */}this happens:
somewhere in RAM: ┌╶╶╶╶╶╶╶╶╶┐ ┆ var bb ┆ └╶╶╶╶╶╶╶╶╶┘ The stack: ┌────────┐ ┌╶╶╶╶╶╶╶╶╶╶╶╶╶╶╶╶╶╶╶╶┐ │ var c╶╶├╶╶╶╶╶╶╶╶╶╶╶┆ /* new function */ ┆ ╞════════╡ └╶╶╶╶╶╶╶╶╶╶╶╶╶╶╶╶╶╶╶╶┘ ┆ ┆As you can see, it's impossible to regain access to the stack frame from the call to
b()since the scope thatcbelongs to doesn't have access to it.
关于javascript - JavaScript 闭包如何在底层工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31735129/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t
我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚
Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack
在选择我想要运行操作的频率时,唯一的选项是“每天”、“每小时”和“每10分钟”。谢谢!我想为我的Rails3.1应用程序运行调度程序。 最佳答案 这不是一个优雅的解决方案,但您可以安排它每天运行,并在实际开始工作之前检查日期是否为当月的第一天。 关于ruby-如何每月在Heroku运行一次Scheduler插件?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/8692687/
我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为