JS匿名函数类生成方式实例分析
网络编程 2021-07-04 19:19www.168986.cn编程入门
这篇文章主要介绍了JS匿名函数类生成方式,结合实例形式分析了javascript匿名函数类相关属性与方法定义与使用技巧,需要的朋友可以参考下
本文实例讲述了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出神入化了,佩服到极致,代码清晰简洁,美观,注释恰到好处。
更多关于JavaScript相关内容可查看本站专题:《》、《》、《》、《》、《》、《》、《》、《》、《》及《》
希望本文所述对大家JavaScript程序设计有所帮助。
编程语言
- 机械手焊接机器人编程 机械手焊接设备编程
- vb数据库编程实例,vb做数据库
- tiobe世界编程语言排行榜,全球编程语言排行
- 成都java编程培训 成都it编程培训中心
- 编程基础培训,编程基础知识培训
- flash游戏编程基础教程,flash游戏开发教程
- 不会英语能学编程吗 不会英语可以学程序员吗
- 爱心代码编程C语言 爱心代码编程c语言公式
- c语言编程学习入门 c语言编程快速入门
- 西门子plc编程培训 西门子plc编程培训班
- 哪里可以学编程 台州哪里可以学编程
- 少儿编程哪个好 少儿编程哪个品牌好
- 编程是什么意思,图形编程是什么意思
- c语言编程软件下载,c语言编程软件在哪下载
- java编程软件下载,java编程下载手机版
- ug编程培训学校,ug编程培训教程