javascript设计模式4

本文介绍了使用JavaScript实现类及静态方法的方法,包括静态成员、特权方法和取值器方法等,并展示了如何通过原型链继承扩展类的功能。

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

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;
};

 

转载于:https://www.cnblogs.com/sdgjytu/p/4209667.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值