ClassScript:靜態、私有與公開屬性

續上一篇「像Java一樣的寫法來宣告JavaScript的Class」簡單的介紹Class的宣告方式,這篇針對屬性的特性做說明,ClassScript除了實作靜態屬性,也實作了封裝的特性,雖然不是百分百模擬其特性,但在使用上就像是封裝的特性。接下來一一說明使用方法:

1.私有屬性 - 使用 var 宣告,直接使用 變數 操作

Class("Animal")(function(){
    var name
 
    this.constructor = function(n){
        name = n
    }
 
    this.getName = function(){
        return name;
    }
 
    this.setName = function(n){
        name = n;
    }
});
 
var oneAnimal = new Animal("狗");
 
alert(oneAnimal.getName()); //→ 顯示 '狗'
alert(oneAnimal.name); //→ 顯示 'undefined' (未定義)

2.公開屬性 - 使用 this. 宣告,使用 this. 作變數操作

Class("Animal")(function(){
    this.name
 
    this.constructor = function(n){
        this.name = n
    }
 
    this.getName = function(){
        return this.name;
    }
 
    this.setName = function(n){
        this.name = n;
    }
});
 
var twoAnimal = new Animal("貓");
 
alert(twoAnimal.getName()); //→ 顯示 '貓'
alert(twoAnimal.name); //→ 顯示 '貓'

3.靜態屬性 - 使用 Static. 宣告,使用this.Statc.類別名稱.變數名稱.作變數操作

Class("Animal")(function(){
    Static.count = 0;
    this.name
 
    this.constructor = function(n){
        this.name = n
        this.Static.count += 1;
    }
 
    this.getName = function(){
        return this.name;
    }
 
    this.setName = function(n){
        this.name = n;
    }
});
 
alert(Animal.count); //→ 0
var oneAnimal = new Animal("狗");
alert(Animal.count); //→ 1
var twoAnimal = new Animal("貓");
alert(Animal.count); //→ 2

回應(Leave a Reply)