Javascript类的写法

Javascript中function即为类,在function内部用this设置类的public成员变量与方法,例如:

view plaincopy to clipboardprint?
function myclass(name){  
    var str = "private string";    //private field  
 
    function privatefn(){      //private method         alert(str);  
    };  
 
    this.name = name;  
 
    this.pubfn = function(){  
        privatefn();      //call private method  
        alert("myclass.pubfn");  
    }  

function myclass(name){
    var str = "private string";    //private field

    function privatefn(){      //private method         alert(str);
    };

    this.name = name;

    this.pubfn = function(){
        privatefn();      //call private method
        alert("myclass.pubfn");
    }
}

使用时用new创建对象:

view plaincopy to clipboardprint?
var obj = new myclass("123");  
var name = obj.name;    //access public field  
obj.pubfn();        //call public method 
var obj = new myclass("123");
var name = obj.name;    //access public field
obj.pubfn();        //call public method

上述是Javascript类最普通的写法,实际应用得较少,用得最多的是写成静态类的形式,Javascript的静态类有两种写法:

1. 类似Json对象的写法

view plaincopy to clipboardprint?
var myclass = {  
    name : "123",  
 
    pubfn : function(){  
        alert("pubfn1 is called");  
    }  
}; 
var myclass = {
    name : "123",

    pubfn : function(){
        alert("pubfn1 is called");
    }
};
 

调用形式:myclass.name, myclass.pubfn()

这种写法使类的成员的访问权限均为public。

2. 匿名函数的写法

view plaincopy to clipboardprint?
var myclass = function(){  
    var name = "123";        //private field  
 
    var privatefn = function(){        //private method  
        alert(name);  
    }  
 
    return{                 //return public field and method  
        Name: "hello " + name,    //public field  
 
        pubfn : function(){  
            privatefn();                //call private method  
            alert("this is a returned function"); //public method  
        }  
    }  
}(); 
var myclass = function(){
    var name = "123";        //private field

    var privatefn = function(){        //private method
        alert(name);
    }

    return{                 //return public field and method
        Name: "hello " + name,    //public field

        pubfn : function(){
            privatefn();                //call private method
            alert("this is a returned function"); //public method
        }
    }
}();

这种写法的好处是可以将私有和共有的成员方法和变量分开,实际应用中可将复杂的逻辑写的私有方法中,而return一个公用的接口调用私有方法。

调用形式:myclass.Name, myclass.pubfn()

注意类结尾处的小括号,它的作用是创建对象,去除小括号的话,则调用形式为:myclass().Name, myclass().pubfn()。

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/Byron0914/archive/2010/04/17/5498056.aspx

posted @ 2011-03-07 09:58  awp110  阅读(208)  评论(0编辑  收藏  举报