zoukankan      html  css  js  c++  java
  • javascript 闭包

    如果没有实战经验,你很难从定义去理解它

    最简单最原始的闭包demo

    javascript 代码

    function A() {
     function B() {
      console.log("Hello");
     }
     return B;
    }
    
    var c = A();
    
    c(); // Hello
    

    在A中返回B的引用
    如果一个对象不再被引用,那么这个对象就会被GC回收,否则这个对象一直会保存在内存中。

    function A() {
     var count = 0;
     function B() {
      count ++;
      console.log(count);
     }
     return B;
    }
    var c = A();
    c(); // 1
    c(); // 2
    

    A中的count一直保存在内存中

    一个简单的demo组件:

    (function(document) {
     var viewport;
     var obj = {
      init: function(id) {
       viewport = document.querySelector("#" + id);
      },
      addChild: function(child) {
       viewport.appendChild(child);
     },
     removeChild: function(child) {
      viewprot.removeChild(child);
     }
     }
     window.jView = obj;
    })(document);
    
    var f = function(document) {
     var viewport;
     var obj = {
      init: function(id) {
       viewport = document.querySelector("#"+id);
      },
      addChild: function(child) {
      viewport.appendChild(child);
      },
      removeChild: function(child) {
      viewport.removeChild(child);
      }
     }
     window.jView = obj;
    };
    f(document);
    

    JS的执行环境(execution context)、活动对象(activation object)以及作用域(scope)和作用域链(scope chain)的运行机制


    请点赞!因为你的鼓励是我写作的最大动力!

    官方微信公众号

    吹逼交流群:711613774

    吹逼交流群

  • 相关阅读:
    How to configure security of ActiveMQ ?
    CentOS 搭建 nginx + tomcat
    25个 Git 进阶技巧
    写给Git初学者的7个建议
    my links
    Shell scripts to Create a local dir base on the time.
    81For全栈技术网
    一款可视化的在线制作H5
    在线制作h5
    在线制作h5——上帝的礼物
  • 原文地址:https://www.cnblogs.com/dashucoding/p/11932376.html
Copyright © 2011-2022 走看看