js 閉包
阿新 • • 發佈:2017-07-24
return 外部 資源 特權 name this 本質 function etc
閉包就是能夠讀取其他函數內部變量的函數。
由於在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),這時一定要小心,不要隨便改變父函數內部變量的值。
js 閉包