Closures

Closures are one of the most powerful features of JavaScript. JavaScript allows for the nesting of functions and grants the inner function full access to all the variables and functions defined inside the outer function (and all other variables and functions that the outer function has access to).

闭包是JavaScript中最强大的特性之一。JavaScript允许函数嵌套,并且内部函数可以访问定义在外部函数中的所有变量和函数,以及外部函数能访问的所有变量和函数。

However, the outer function does not have access to the variables and functions defined inside the inner function. This provides a sort of encapsulation for the variables of the inner function.

然而,外部函数却不能访问定义在内部函数的变量和函数。这给内部函数的变量提供了一定的安全性

Also, since the inner function has access to the scope of the outer function, the variables and functions defined in the outer function will live longer than the duration of the outer function execution, if the inner function manages to survive beyond the life of the outer function. A closure is created when the inner function is somehow made available to any scope outside the outer function.

此外,由于内部函数可以访问外部函数的作用域,因此当内部函数生存周期大于外部函数时,外部函数中定义的变量和函数的生命周期将比内部函数执行时间长。当内部函数以某一种方式被任何外部函数作用域访问时,一个闭包就产生了

var pet = function(name) { // The outer function defines a variable called "name"
var getName = function() {
return name; // The inner function has access to the "name" variable of the outer function
}
return getName; // Return the inner function, there by exposing it to outer scopes
}
myPet = pet('Vivie'); console.log(myPet()); // Returns "Vivie"

It can be much more complex than the code above. An object containing methods for manipulating the inner variables of the outer function can be returned.

它可能比上面的代码复杂的多。可以返回包含操作外部函数内部变量的方法的对象

var createPet = function (name) {
var sex; return {
setName: function(newName) {
name = newName;
}, getName: function() {
return name;
}, setSex: function(newSex) {
if (typeof newSex === 'string' && (newSex.toLowerCase() === 'male' || newSex.toLowerCase() === 'female')) {
sex = newSex;
}
}, getSex: function () {
return sex;
}
}
} var pet = createPet('Vivie');
console.log(pet.getName()); pet.setName('Oliver');
pet.setSex('male');
console.log(pet.getSex());
console.log(pet.getName());

最新文章

  1. HBase数据库集群配置
  2. ORACLE动态采样分析
  3. Jenkins进阶系列之——04Publish Over FTP Plugin插件
  4. [Arduino+Android] 自制土砲智能安全帽
  5. 常用 xwt 工具
  6. 关于Kingfisher--备用
  7. SQL_SERVER日期函数详细用法
  8. bash:xxx:command not found
  9. 【高德地图API】汇润做爱地图技术大揭秘
  10. Net Core 生成图形验证码
  11. VB 字符串转换为UTF-8
  12. 《Kubernetes权威指南》——运维技巧
  13. bootstrap 文本对齐风格
  14. JobScheduler android任务调度处理组件(类似QuartZ)
  15. yum第三方安装-软件包没签名及更新错误
  16. 重读源码,见证HashMap以及它的朋友们的骚操作
  17. ETL工作流缓慢原因查找方法
  18. list详解
  19. 二进制、十进制、十六进制(python)
  20. 【CF1023E】Down or Right(交互,贪心)

热门文章

  1. sed 和 awk
  2. 利用CRM实现电话营销部门的管控 之数据暂缓
  3. TCP 3-Way Handshake
  4. ACM学习总结 6月11日
  5. [bzoj2088]P3505 [POI2010]TEL-Teleportation
  6. FarmCraft
  7. 《Docker从入门到跑路》之简介
  8. 面向开发者的Docker实践
  9. Android Bluetooth How To--Based on Android L Bluedroid
  10. acm的一些头文件和调试代码