JS匿名函数类生成方式实例分析
本文实例讲述了JS匿名函数类生成方式。分享给大家供大家参考,具体如下:
<scripttype="text/javascript"> varBook=(function(){ //私有静态属性 varnumOfBooks=0; //私有静态方法 functioncheckIsbn(isbn){ if(isbn==undefined||typeofisbn!='string'){ returnfalse; } returntrue; } //返回构造函数 returnfunction(newIsbn,newTitle,newAuthor){//implementsPublication //私有属性 varisbn,title,author; //特权方法 this.getIsbn=function(){ returnisbn; }; this.setIsbn=function(newIsbn){ if(!checkIsbn(newIsbn))thrownewError('Book:InvalidISBN.'); isbn=newIsbn; }; this.getTitle=function(){ returntitle; }; this.setTitle=function(newTitle){ title=newTitle||'Notitlespecified'; }; this.getAuthor=function(){ returnauthor; }; this.setAuthor=function(newAuthor){ author=newAuthor||'Noauthorspecified'; }; //控制对象数目,构造函数 numOfBooks++;//KeeptrackofhowmanyBookshavebeeninstantiated //withtheprivatestaticattribute. if(numOfBooks>5)thrownewError('Book:Only5instancesofBookcanbe' +'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()); } }; //vartheHobbit=newBook(123,'','J.R.R.Tolkein');//非字符串抛出异常 vartheHobbit=newBook('1990-78sd-1092','','J.R.R.Tolkein'); theHobbit.display(); //theHobbit.convertToTitleCase();//UncaughtTypeError:Object#<Object>hasnomethod'convertToTitleCase' Book.convertToTitleCase();//输出convertToTitleCase vartheHobbit2=newBook('1990-78sd-1092','','J.R.R.Tolkein'); theHobbit2.display(); vartheHobbit3=newBook('1990-78sd-1092','','J.R.R.Tolkein'); theHobbit3.display(); vartheHobbit4=newBook('1990-78sd-1092','','J.R.R.Tolkein'); theHobbit4.display(); vartheHobbit5=newBook('1990-78sd-1092','','J.R.R.Tolkein'); theHobbit5.display(); vartheHobbit6=newBook('1990-78sd-1092','','J.R.R.Tolkein'); theHobbit6.display();//UncaughtError:Book:Only5instancesofBookcanbecreated. </script>
这里已经把js出神入化了,佩服到极致,代码清晰简洁,美观,注释恰到好处。
更多关于JavaScript相关内容可查看本站专题:《JavaScript常用函数技巧汇总》、《javascript面向对象入门教程》、《JavaScript中json操作技巧总结》、《JavaScript切换特效与技巧总结》、《JavaScript查找算法技巧总结》、《JavaScript动画特效与技巧汇总》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结》
希望本文所述对大家JavaScript程序设计有所帮助。