首页 > web前端 > js教程 > 正文

JS匿名函数类生成方式实例分析

高洛峰
发布: 2016-12-05 10:15:52
原创
1144人浏览过

本文实例讲述了js匿名函数类生成方式。分享给大家供大家参考,具体如下:

<script type="text/javascript">
var Book = (function() {
 // 私有静态属性
 var numOfBooks = 0;
 // 私有静态方法
 function checkIsbn(isbn) {
  if(isbn == undefined || typeof isbn != 'string') {
   return false;
  }
  return true;
 }
 // 返回构造函数
 return function(newIsbn, newTitle, newAuthor) { // implements Publication
  // 私有属性
  var isbn, title, author;
  // 特权方法
  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';
  };
  // 控制对象数目,构造函数
  numOfBooks++; // Keep track of how many Books have been instantiated
         // with the private static attribute.
  if(numOfBooks > 5) throw new Error('Book: Only 5 instances of Book can be '
    + 'created.');
  this.setIsbn(newIsbn);
  this.setTitle(newTitle);
  this.setAuthor(newAuthor);
 }
})();
// 公有静态方法
Book.convertToTitleCase = function(inputString) {
 alert('convertToTitleCase');
};
// 公有非特权方法
Book.prototype = {
 display: function() {
  alert("isbn:"+this.getIsbn()+" title:"+this.getTitle()+" author:"+this.getAuthor());
 }
};
//var theHobbit = new Book(123, '', 'J. R. R. Tolkein'); // 非字符串抛出异常
var theHobbit = new Book('1990-78sd-1092', '', 'J. R. R. Tolkein');
theHobbit.display();
//theHobbit.convertToTitleCase(); // Uncaught TypeError: Object #<Object> has no method 'convertToTitleCase'
Book.convertToTitleCase(); // 输出convertToTitleCase
var theHobbit2 = new Book('1990-78sd-1092', '', 'J. R. R. Tolkein');
theHobbit2.display();
var theHobbit3 = new Book('1990-78sd-1092', '', 'J. R. R. Tolkein');
theHobbit3.display();
var theHobbit4 = new Book('1990-78sd-1092', '', 'J. R. R. Tolkein');
theHobbit4.display();
var theHobbit5 = new Book('1990-78sd-1092', '', 'J. R. R. Tolkein');
theHobbit5.display();
var theHobbit6 = new Book('1990-78sd-1092', '', 'J. R. R. Tolkein');
theHobbit6.display(); // Uncaught Error: Book: Only 5 instances of Book can be created.
</script>
登录后复制

这里已经把js出神入化了,佩服到极致,代码清晰简洁,美观,注释恰到好处。

GPTKit
GPTKit

一个AI文本生成检测工具

GPTKit 108
查看详情 GPTKit
相关标签:
js
最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号