7.2使用闭包定义私有变量 this对象(JavaScript高级程序设计总结)

闭包

有权访问另一个函数作用域中的变量的函数。
当某个函数被调用时,会创建一个执行环境及相应的作用域链。当函数执行完毕后,局部活动对象就会被销毁,内存中仅保存全局作用域。但是闭包不同。
当外部函数执行完后,其执行环境的作用域链会被销毁,但它的活动对象仍然会保留在内存中。直到匿名函数被销毁后,外部函数的活动对象才会被销毁。

闭包只能取得包含函数中任何变量的最后值


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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章