閉包
有權訪問另一個函數作用域中的變量的函數。
當某個函數被調用時,會創建一個執行環境及相應的作用域鏈。當函數執行完畢後,局部活動對象就會被銷燬,內存中僅保存全局作用域。但是閉包不同。
當外部函數執行完後,其執行環境的作用域鏈會被銷燬,但它的活動對象仍然會保留在內存中。直到匿名函數被銷燬後,外部函數的活動對象纔會被銷燬。
閉包只能取得包含函數中任何變量的最後值
const createArray = () => {
const arr = [];
for (var i = 0; i < 10; i += 1) {
arr[i] = function () {
return i;
};
}
return arr;
}
createArray().forEach((item) => {
console.log(item()); // 10
})
通過創建另一個匿名函數,則可以達到預期
const createArray = () => {
const arr = [];
for (var i = 0; i < 10; i += 1) {
arr[i] = function (num) {
return function () {
return num;
}
}(i);
}
return arr;
}
createArray().forEach((item) => {
console.log(item()); // 0-9
})
this
this對象是在運行時基於函數的執行環境綁定的
匿名函數的執行環境具有全局性
var name = 'Sam';
const person = {
name: 'Tom',
getName() {
return function () {
return this.name;
}
}
}
console.log(person.getName()()) // Sam
模仿塊級作用域
(function () {
// 塊級作用域
})();
私有變量
特權方法:利用閉包通過自己的作用域鏈也可以訪問私有變量
構造函數方法
function MyObject(name) {
let _variable = 10;
function getVar() {
return `${_variable}and${name}`;
}
this.publicMethod = function (value) {
_variable += 1;
name = value;
return getVar();
}
}
const my = new MyObject('Sam');
console.log(my.publicMethod('Tom')) // 11andTom
缺點:針對每個實例都會創建同樣一組新方法
靜態私有變量
const that = function () {
return this;
}();
(function () {
let name = '';
that.Person = function (value) {
name = value;
}
that.Person.prototype.getName = function () {
return name;
}
that.Person.prototype.setName = function (value) {
name = value;
}
})();
const personFirst = new that.Person('sam');
console.log(personFirst.getName()) // sam
const personSecond = new that.Person("Tom");
console.log(personFirst.getName()) // Tom
console.log(personSecond.getName()) // Tom