Closures Basic
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());