2009-05-30

[JavaScript] 物件導向-類別宣告


// 宣告類別
function Attack(key) {
/*=( 建構子及初始化成員變數 )================== */
// 設定字符表
this.keyStr = key;

// 將字串切割成陣列
this.keyArray = this.keyStr.match(/./gi);

// 進位基底
this.base = this.keyArray.length;

this.passwd = [0];


/*=( 成員函數 )================== */
// 前進一個字符
this.pushPasswd = function(){
var p = this.passwd;
var b = this.base;
var i = 0;

p[i]++;
while(p[i] >= b){
p[i++] = 0;
if(p[i] != undefined){
p[i]++;
}else{
p[i] = 0;
}

}
return this;
};

// 設定初始字串
this.setPasswd = function(str){
this.passwd = [0];

if(str){
var s = str.match(/./gi);
var k = this.keyStr;

for(var i=0,l=s.length; i<l; i++){
num = k.indexOf( str[i] );
if(num<0){ num = 0; }
this.passwd[l-i-1] = num;
}
}
return this;
};

// 取得當前字串
this.getPasswd = function(){
var temp = '';
var k = this.keyArray;
var p = this.passwd;

for(var i=0,l=p.length; i<l; i++){
temp = k[ p[i] ] + temp;
}
return temp;

};
}


// 建立物件
var try1 = new Attack('abcdefghijklmnopqrstuvwxyz0123456789');

// 物件操作
try1.setPasswd('asdf');
try1.getPasswd();

0 回應: