我们以Book类为例,Book类有三个属性:书号、标题、作者
Code
这样一个简单的Book类就创建好了

我们可以这样实例化这个类
var book = new Book(111,"基本型","zixinhmc");
book.display();

上面的类有一个问题,我们在实例化时,并没有对ISBN 属性进行数据完整性验证,我们修改一下上面的那个类
var Book = function(isbn,title,author){
    
if(!this.checkIsbn(isbn)){
        
throw new Error("isbn错误");
    }
    
this.isbn = isbn;
    
this.title = title;
    
this.author = author;
}
Book.prototype 
= {
    checkIsbn:
function(isbn){
        
if(isbn == undefined || typeof isbn != "string"){
            
return false;
        }
        
if(isbn.length != 10){
            
return false;
        }
        
return true;
    }
    , display:
function(){
        alert(
"isbn:" + this.isbn + "\n" + "title:" + this.title + "\n" + "author:" + this.author);
    }
}
现在情况看起来有所改善了,我们在实例化对象时对ISBN属性进行有效性检查,如果不通过将抛出一个异常。
但是,现在又出现一个问题了
我们看
var book = new Book("1234567890","基本型","zixinhmc");
book.isbn 
= 1;
book.display();
我们现在可以在实例化了以后,给对象的isbn属性赋值,而这时的赋值将不会进行有效性验证,所以我们将再次修改这个类,给这三个属性添加get、set方法,让用户不能直接操作这个类的属性
var Book = function(isbn,title,author){
    
this.setIsbn(isbn);
    
this.setTitle(title);
    
this.setAuthor(author);
}
Book.prototype 
={
    checkIsbn: 
function(isbn){
        
if(isbn == undefined || typeof isbn != "string"){
            
return false;
        }
        
if(isbn.length != 10){
            
return false;
        }
        
return true;
    }
    , getIsbn: 
function(){
        
return this._isbn;
    }
    , setIsbn: 
function(isbn){
        
if(!this.checkIsbn(isbn)){
            
throw new error("isbn错误");
        }
        
this._isbn = isbn;
    }
    , getTitle: 
function(){
        
return this._title;
    }
    , setTitle: 
function(title){
        
this._title = title;
    }
    , getAuthor: 
function(){
        
return this._author;
    }
    , setAuthor: 
function(author){
        
this._author = author;
    }
    , display:
function(){
        alert(
"isbn:" + this.isbn + "\n" + "title:" + this.title + "\n" + "author:" + this.author);
    }
};
我们现在可以使用setIsbn()来给属性赋值了
var book = new Book("1234567890","门户打开型","zixinhmc");
book.setIsbn(
"0123456789");
book.display();

注意:其实,实例化后还是可以通过book._isbn来绕过检查给属性赋值的,不过,我们一般在团队内部约定以下划线(_)为前缀的属性或方法为私有,不要直接赋值或调用
我们将在下一次讲解如何创建真正拥有私有属性或方法的类

参考书目:
《JavaScript权威指南》
《JavaScritp高级程序设计》
《JavaScript设计模式》
posted on 2009-08-27 16:38  滋心  阅读(306)  评论(0编辑  收藏  举报