当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JS闭包原理与应用经典示例

JS闭包原理与应用经典示例

2019年01月04日  | 移动技术网IT编程  | 我要评论

本文实例讲述了js闭包原理与应用。分享给大家供大家参考,具体如下:

一、先来看一个例子:

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代码运行工具:测试上述代码,可得到如下运行结果:

一直以来,我都是以为只有用匿名函数才能算是闭包,但是其实不一定要用匿名函数的,就是一般的函数就可以,前提是它得被包含在另一个函数中。

在foo返回后,它的作用域被保存下来了,但只有它返回的的那个函数能够访问这个作用域。在前面的示例中,baz和balt各有各的作用域及a的一个副本,而且只有他们自己能对其进行修改。

其实就是说我们对foo函数的引用的调用并不会对其他引用有任何影响。

二、封装和隐藏信息

看了上面的例子,我们可以考虑采用匿名函数来进行封装和隐藏私有变量。

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代码运行工具:测试上述代码,可得到如下运行结果:

我们通过在构造器中用var声明了这些变量和checkisbn函数,因此他们就变成了私有的属性。需要访问这些变量和函数的方法只需要在book中声明即可。这些方法也被陈伟特权方法。而任何不需要访问私有属性的方法都要在book.prototype中声明。例如display。但这里也存在个问题:就是每生成一个新的对象实例都将为每一个私有方法和特权方法生成一个新的副本。这会比其他做法耗费更多内存,因此只宜用在真正需要私有成员的场合。另外,这种模式也不适合派生子类,因为派生的子类并不能访问超类的任何私有属性和方法。故在javascript中用闭包实现私有成员导致派生问题被称为“继承破坏封装”。

三、改进

这里与上一种大体类似,但是也有一些重要的区别。这里私有成员和特权成员仍被声明在构造器中,但是构造器已经变成一个内嵌函数了,并且被作为包含它的函数的返回值赋给变量book.这就是创建了一个闭包,你可以把静态的私有成员函数声明在里面。

checkisbn函数被设置为静态方法,是因为没必要为每个实例都生成这个方法的一个副本。此外还有静态属性numbooks限制了构造器总的调用次数

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代码运行工具:测试上述代码,可得到如下运行结果:

更多关于javascript相关内容感兴趣的读者可查看本站专题:《javascript面向对象入门教程》、《javascript错误与调试技巧总结》、《javascript数据结构与算法技巧总结》、《javascript遍历算法与技巧总结》及《javascript数学运算用法总结

希望本文所述对大家javascript程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网