一条小码农

努力一点,现在想要的未来都会有。

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),这时一定要小心,不要随便改变父函数内部变量的值。
posted @ 2017-07-24 15:26  萝卜的博  阅读(322)  评论(0编辑  收藏  举报