我也谈javascript闭包

1、什么是闭包呢?Whenever you see the function keyword within another function, the inner function has access to variables in the outer function

function foo(x) {
  var tmp = 3;

  return function (y) {
    alert(x + y + (++tmp)); // will also alert 16
  }
}

var bar = foo(2); // bar is now a closure.
bar(10);

/*
*    When a function is defined in another function and it
*    has access to the outer function‘s context even after
*    the outer function returns.
*
* An important concept to learn in JavaScript.
*/

function outerFunction(someNum) {
    var someString = ‘Hey!‘;
    var content = document.getElementById(‘content‘);
    function innerFunction() {
        content.innerHTML = someNum + ‘: ‘ + someString;
        content = null; // Internet Explorer memory leak for DOM reference
    }
    innerFunction();
}

outerFunction(1);?

Two one sentence summaries:

  • a closure is the local variables for a function — kept alive after the function has returned, or
  • a closure is 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!).

The following code returns a reference to a function:

function sayHello2(name) {
    var text = ‘Hello ‘ + name; // Local variable
    var sayAlert = function() { alert(text); }
    return sayAlert;
}
say2 = sayHello2(‘Bob‘);
say2();

Most JavaScript programmers will understand how a reference to a function is returned to a variable in the above code. If you don‘t, then you need to before you can learn closures. A C programmer would think of the function as returning a pointer to a function, and that the variables sayAlert and say2were each a pointer to a function.

There is a critical difference between a C pointer to a function and a JavaScript reference to a function. In JavaScript, you can think of a function reference variable as having both a pointer to a function as well as a hidden pointer to a closure.

The above code has a closure because the anonymous function function() { alert(text); } is declared inside another function, sayHello2() in this example. In JavaScript, if you use the functionkeyword inside another function, you are creating a closure.

In C, and most other common languages after a function returns, all the local variables are no longer accessible because the stack-frame is destroyed.

In JavaScript, if you declare a function within another function, then the local variables can remain accessible after returning from the function you called. This is demonstrated above, because we call the function say2() after we have returned from sayHello2(). Notice that the code that we call references the variable text, which was a local variable of the function sayHello2().

function() { alert(text); } // Output of say2.toString();

Click the button above to get JavaScript to print out the code for the anonymous function. You can see that the code refers to the variable text. The anonymous function can reference text which holds the value ‘Bob‘ because the local variables of sayHello2() are kept in a closure.

The magic is that in JavaScript a function reference also has a secret reference to the closure it was created in — similar to how delegates are a method pointer plus a secret reference to an object.

 
 
时间: 2024-08-26 05:12:54

我也谈javascript闭包的相关文章

浅谈JavaScript闭包

一.背景知识 在介绍闭包之前,我觉得有必要先简单的介绍一些背景知识,如变量的作用域.嵌套函数.垃圾回收机制等概念. 1.作用域 作用域是程序运行时变量可被访问的范围,定义在函数内的的变量是局部变量,局部变量的作用域只能是函数内部范围内,它不能在函数外引用.定义在模块最外层的的变量是全局变量,它是全局范围内可见的,当然在函数里面也可以读取到全局变量的. var a = 123; //全局变量 function fun(){ var b = 456; //局部变量 } 2.嵌套函数 函数不仅可以定义

浅谈JavaScript闭包、this指针、作用域(一)

认识闭包: 闭包,是指有权限访问到其他函数作用域的变量的函数 给一个例子: function outer () { var name = 'HelloTF'; return function () { console.log (name); } } var getName = outer(); getName(); //HelloTF 函数outer执行后返回一个内部的匿名函数,并把返回的结果赋值给全局变量result,在全局环境中在此执行result,得到了outer函数内部的变量name.

再谈JavaScript闭包及应用

写在前面 本文章版权归博客园和作者共同所有,转载请注明原文地址博客园吴双 http://www.cnblogs.com/tdws/ 闭包真的是学过一遍又一遍,Js博大精深,每次学习都感觉有新的收获.相信在大家封装前端插件时,闭包是必不可少的.闭包的真正好处我个人认为除了封装还是封装,能带个我们私有方法,和调用上的灵活方便,也会使你的代码对外的对象保持干净整洁. 进入正题 维基百科这样定义了JS闭包:在计算机科学中,闭包(英语:Closure),又称词法闭包(Lexical Closure)或函数

《浅谈JavaScript系列》系列技术文章整理收藏

<浅谈JavaScript系列>系列技术文章整理收藏 1浅谈JavaScript中面向对象技术的模拟 2浅谈javascript函数劫持[转自xfocus]第1/3页 3浅谈javascript 面向对象编程 4老鱼 浅谈javascript面向对象编程 5浅谈javascript的数据类型检测 6浅谈Javascript嵌套函数及闭包 7根据一段代码浅谈Javascript闭包 8浅谈JavaScript编程语言的编码规范 9浅谈Javascript面向对象编程 10浅谈JavaScript

再谈JavaScript的closure--JavaScript 闭包

关于JavaScript的闭包,在我的博客上之前有一篇文章 https://www.cnblogs.com/wphl-27/p/8491327.html 今天看了几篇文章,感觉又有了一些更深的理解,特记录如下: 其实关于JavaScript的闭包closure, 简单点理解可以如下: 在JavaScript中,一个函数A内部又包含一个函数B, 同时把内部函数B作为函数A的返回值,这个时候,就形成了一个闭包. 我们来看一个简单的例子: var a = 5; function TestAdd(){

JavaScript 闭包究竟是什么

JavaScript 闭包究竟是什么 1.简单的例子 首先从一个经典错误谈起,页面上有若干个div, 我们想给它们绑定一个onclick方法,于是有了下面的代码 <div id="divTest"> <span>0</span> <span>1</span> <span>2</span> <span>3</span> </div> <div id="d

深入解析Javascript闭包

首先给个例子: function PfnOuter(){ var num=999; function PfnInner(){ alert(num); } return PfnInner; } var test=PfnOuter(); test(); //999 上述实例中PfnInner函数就是闭包,闭包简单的理解就是能够读取其它函数内部变量的函数.由于Javascript中只有函数内部的子函数才能读取函数内部的变量,因此闭包也可以简单的理解成定义在一个函数内部的函数,闭包就是将函数内部和函数外

再谈javascript面向对象编程

前言:虽有陈皓<Javascript 面向对象编程>珠玉在前,但是我还是忍不住再画蛇添足的补上一篇文章,主要是因为javascript这门语言魅力.另外这篇文章是一篇入门文章,我也是才开始学习Javascript,有一点心得,才想写一篇这样文章,文章中难免有错误的地方,还请各位不吝吐槽指正 吐槽Javascript 初次接触Javascript,这门语言的确会让很多正规军感到诸多的不适,这种不适来自于Javascript的语法的简练和不严谨,这种不适也 来自Javascript这个悲催的名称,

JavaScript闭包其一:闭包概论 函数式编程中一些基本定义

http://www.nowamagic.net/librarys/veda/detail/1707前面介绍了作用域链和变量对象,现在再讲闭包就容易理解了.闭包其实大家都已经谈烂了.尽管如此,这里还是要试着从理论角度来讨论下闭包,看看ECMAScript中的闭包内部究竟是如何工作的. 在直接讨论ECMAScript闭包之前,还是有必要来看一下函数式编程中一些基本定义. 众所周知,在函数式语言中(ECMAScript也支持这种风格),函数即是数据.就比方说,函数可以赋值给变量,可以当参数传递给其他