亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

JS閉包原理與應(yīng)用經(jīng)典示例

 更新時(shí)間:2018年12月20日 10:25:03   作者:huansky  
這篇文章主要介紹了JS閉包原理與應(yīng)用,結(jié)合實(shí)例形式較為詳細(xì)的分析了javascript閉包的原理、應(yīng)用及相關(guān)操作注意事項(xiàng),需要的朋友可以參考下

本文實(shí)例講述了JS閉包原理與應(yīng)用。分享給大家供大家參考,具體如下:

一、先來(lái)看一個(gè)例子:

function foo() {
   var a = 10;
   function bar() {
    a *= 2;
    return a;
   }
   return bar;
}
var baz = foo(); // baz is now a reference to function bar.
console.log(baz()); // returns 20.
console.log(baz()); // returns 40.
console.log(baz()); // returns 80.
var blat = foo(); // blat is another reference to bar.
console.log(blat()); // returns 20, because a new copy of a is being used.

這里使用在線HTML/CSS/JavaScript代碼運(yùn)行工具http://tools.jb51.net/code/HtmlJsRun測(cè)試上述代碼,可得到如下運(yùn)行結(jié)果:

一直以來(lái),我都是以為只有用匿名函數(shù)才能算是閉包,但是其實(shí)不一定要用匿名函數(shù)的,就是一般的函數(shù)就可以,前提是它得被包含在另一個(gè)函數(shù)中。

在foo返回后,它的作用域被保存下來(lái)了,但只有它返回的的那個(gè)函數(shù)能夠訪問(wèn)這個(gè)作用域。在前面的示例中,baz和balt各有各的作用域及a的一個(gè)副本,而且只有他們自己能對(duì)其進(jìn)行修改。

其實(shí)就是說(shuō)我們對(duì)foo函數(shù)的引用的調(diào)用并不會(huì)對(duì)其他引用有任何影響。

二、封裝和隱藏信息

看了上面的例子,我們可以考慮采用匿名函數(shù)來(lái)進(jìn)行封裝和隱藏私有變量。

var Book = function(newIsbn, newTitle, newAuthor) { // implements Publication
 // Private attributes.
 var isbn, title, author;
 // Private method.
 function checkIsbn(isbn) {
  //...
  return true;
 }
 // Privileged methods.
 this.getIsbn = function() {
  return isbn;
 };
 this.setIsbn = function(newIsbn) {
  if(!checkIsbn(newIsbn)) throw new Error('Book: Invalid ISBN.');
  isbn = newIsbn;
 };
 this.getTitle = function() {
  return title;
 };
 this.setTitle = function(newTitle) {
  title = newTitle || 'No title specified';
 };
 this.getAuthor = function() {
  return author;
 };
 this.setAuthor = function(newAuthor) {
  author = newAuthor || 'No author specified';
 };
 // Constructor code.
 this.setIsbn(newIsbn);
 this.setTitle(newTitle);
 this.setAuthor(newAuthor);
};
// Public, non-privileged methods.
Book.prototype = {
 display: function() {
  //...
 }
};
var mybook=new Book("myisbtn","mytittle","myauthor");
console.log(mybook.getAuthor());

使用在線HTML/CSS/JavaScript代碼運(yùn)行工具http://tools.jb51.net/code/HtmlJsRun測(cè)試上述代碼,可得到如下運(yùn)行結(jié)果:

我們通過(guò)在構(gòu)造器中用var聲明了這些變量和checkIsbn函數(shù),因此他們就變成了私有的屬性。需要訪問(wèn)這些變量和函數(shù)的方法只需要在Book中聲明即可。這些方法也被陳偉特權(quán)方法。而任何不需要訪問(wèn)私有屬性的方法都要在Book.prototype中聲明。例如display。但這里也存在個(gè)問(wèn)題:就是每生成一個(gè)新的對(duì)象實(shí)例都將為每一個(gè)私有方法和特權(quán)方法生成一個(gè)新的副本。這會(huì)比其他做法耗費(fèi)更多內(nèi)存,因此只宜用在真正需要私有成員的場(chǎng)合。另外,這種模式也不適合派生子類,因?yàn)榕缮淖宇惒⒉荒茉L問(wèn)超類的任何私有屬性和方法。故在JavaScript中用閉包實(shí)現(xiàn)私有成員導(dǎo)致派生問(wèn)題被稱為“繼承破壞封裝”。

三、改進(jìn)

這里與上一種大體類似,但是也有一些重要的區(qū)別。這里私有成員和特權(quán)成員仍被聲明在構(gòu)造器中,但是構(gòu)造器已經(jīng)變成一個(gè)內(nèi)嵌函數(shù)了,并且被作為包含它的函數(shù)的返回值賦給變量Book.這就是創(chuàng)建了一個(gè)閉包,你可以把靜態(tài)的私有成員函數(shù)聲明在里面。

checkIsbn函數(shù)被設(shè)置為靜態(tài)方法,是因?yàn)闆](méi)必要為每個(gè)實(shí)例都生成這個(gè)方法的一個(gè)副本。此外還有靜態(tài)屬性numBooks限制了構(gòu)造器總的調(diào)用次數(shù)

var Book = (function() {
 // Private static attributes.
 var numOfBooks = 0;
 // Private static method.
 function checkIsbn(isbn) {
  // ...
  return true;
 }
 // Return the constructor.
 return function(newIsbn, newTitle, newAuthor) { // implements Publication
  // Private attributes.
  var isbn, title, author;
  // Privileged methods.
  this.getIsbn = function() {
   return isbn;
  };
  this.setIsbn = function(newIsbn) {
   if(!checkIsbn(newIsbn)) throw new Error('Book: Invalid ISBN.');
   isbn = newIsbn;
  };
  this.getTitle = function() {
   return title;
  };
  this.setTitle = function(newTitle) {
   title = newTitle || 'No title specified';
  };
  this.getAuthor = function() {
   return author;
  };
  this.setAuthor = function(newAuthor) {
   author = newAuthor || 'No author specified';
  };
  // Constructor code.
  numOfBooks++; // Keep track of how many Books have been instantiated
         // with the private static attribute.
  if(numOfBooks > 1) throw new Error('Book: Only 1 instances of Book can be '
    + 'created.');
  this.setIsbn(newIsbn);
  this.setTitle(newTitle);
  this.setAuthor(newAuthor);
 }
})();
// Public static method.
Book.convertToTitleCase = function(inputString) {
 //...
 console.log("convertToTitleCase");
};
// Public, non-privileged methods.
Book.prototype = {
 display: function() {
  //...
  console.log("display");
 }
};
var mybook=new Book("myisbtn","mytittle","myauthor");
console.log(mybook.getAuthor());  //myauthor
mybook.display();          //display
//mybook.convertToTitleCase();   //mybook.convertToTitleCase is not a function
var mybook2= new Book("my2","tittle2","myauthor2");
console.log(mybook2.getAuthor());  //Only 1 instances of Book can be created.

使用在線HTML/CSS/JavaScript代碼運(yùn)行工具http://tools.jb51.net/code/HtmlJsRun測(cè)試上述代碼,可得到如下運(yùn)行結(jié)果:

更多關(guān)于JavaScript相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《javascript面向?qū)ο笕腴T教程》、《JavaScript錯(cuò)誤與調(diào)試技巧總結(jié)》、《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》、《JavaScript遍歷算法與技巧總結(jié)》及《JavaScript數(shù)學(xué)運(yùn)算用法總結(jié)

希望本文所述對(duì)大家JavaScript程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論