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

    闭包就是能够读取其他函数内部变量的函数。
     
    由于在Javascript语言中,只有函数内部的子函数才能读取局部变量,因此可以把闭包简单理解成"定义在一个函数内部的函数"。
     
    所以,在本质上,闭包就是将函数内部和函数外部连接起来的一座桥梁。
     
     
    varBook=(function(){
    //静态资源变量
    var press="中央出版社";
    //静态方法
    var text=function(){};
    function _book(id,content,name){
    //私有属性
    var name=press+"";
    //私有方法
    var checkBook=function(){
    console.log('-------'+name);
    }
    //特权方法
    this.setContent=function(){};
    this.getContent=function(){};
    //公有属性
    this.id=id;
    this.setContent(content);
    //共有方法
    this.test=function(name){
    console.log('--++++'+press+name);
    }
    }
    _book.prototype={
    test2:function(){ console.log("prototype");}
    }
    return _book;
    })();
    var book=newBook(12,'内容','名字');
    console.log(book.id);
    book.test('name');
    book.test2();
    console.log(Book.name);
    

      

    使用闭包的注意点:
    1)由于闭包会使得函数中的变量都被保存在内存中,内存消耗很大,所以不能滥用闭包,否则会造成网页的性能问题,在IE中可能导致内存泄露。解决方法是,在退出函数之前,将不使用的局部变量全部删除。
    2)闭包会在父函数外部,改变父函数内部变量的值。所以,如果你把父函数当作对象(object)使用,把闭包当作它的公用方法(Public Method),把内部变量当作它的私有属性(private value),这时一定要小心,不要随便改变父函数内部变量的值。
  • 相关阅读:
    202. Happy Number
    198. House Robber
    191. Number of 1 Bits
    190. Reverse Bits
    189. Rotate Array
    172. Factorial Trailing Zeroes
    171. Excel Sheet Column Number
    [leetcode]Single Number II
    [leetcode]Single Number
    [leetcode]Clone Graph
  • 原文地址:https://www.cnblogs.com/QQ-Monarch/p/7229159.html
Copyright © 2011-2022 走看看