首页 > 代码库 > javascript设计模式4

javascript设计模式4

静态成员是直接通过类对象访问的

var Book=(function(){    var numOfBooks=0;    function checkIsbn(isbn){        ...    }    return function(newIsbn,newTitle,newAuthor){        var isbn,title,author;        this.getIsbn=function(){            return isbn;        };        this.setIsbn=function(newIsbn){            if(!checkIsbn(newIsbn)) throw new Error(‘ISBN不合法‘);            isbn=newIsbn;        };        this.getTitle=function(){            return title;        };        this.setTitle=function(newTitle){            title=newTitle||‘无标题‘;        };        this.getAuthor=function(){            return author;        };        this.setAuthor=function(newAuthor){            author=newAuthor||‘无作者‘;        };        numOfBooks++;        if(numOfBooks>50) throw new Error(‘只能创建50个实例‘);        this.setIsbn(newIsbn);        this.setTitle(newTitle);        this.setAuthor(newAuthor);    }})();Book.convertToTitleCase=function(inputString){    ...};Book.prototype={    display:function(){        ...    }};

 静态特权方法(模仿常量)

//Class.getUPPER_BOUND();var Class=(function(){    var UPPER_BOUND=100;    var ctor=function(constructorArgument){        ...    };    ctor.getUPPER_BOUND=function(){        return UPPER_BOUND;    };    ...    return ctor;})();

通用的取值器方法

//Class.getConstant(‘UPPER_BOUND‘);var Class=(function(){    var constants={        UPPER_BOUND:100,        LOWER_BOUND:-100    };    var ctor=function(constructorArgument){        ...    };    ctor.getConstant=function(name){        return constants[name];    };    ...    return ctor;})();

原型链

function Author(name,books){    Person.call(this,name);    this.books=books;}Author.prototype=new Person();Author.prototype.constructor=Author;Author.prototype.getBooks = function() {    return this.books;};

 

javascript设计模式4