JavaScript 中實現私有屬性的寫類方式
[1] JavaScript 中實現私有屬性的寫類方式
[2] JavaScript 中實現私有屬性的寫類方式
[2] JavaScript 中實現私有屬性的寫類方式
之前討論過JavaScript中的寫類方式。但沒有討論私有的實現。這篇看下。
我們知道JS中私有屬性的實現本質就是 var + closure。如下:
function Person(n, a){
// public
this.name = n;
// private
var age = a;
this.getName = function(){
return this.name;
}
this.getAge = function(){
return age;
}
}
// public
this.name = n;
// private
var age = a;
this.getName = function(){
return this.name;
}
this.getAge = function(){
return age;
}
}
測試如下,age是私有的,使用點操作符無法獲取到,而只能使用getName方法。
var p = new Person('jack',23);
console.log(p.age); // undefined
console.log(p.getAge()); // 23
console.log(p.age); // undefined
console.log(p.getAge()); // 23
以上沒什么稀奇的,下面我們使用一個工具函數來實現。
/**
* @param {String} className
* @param {Function} classImp
*/
function $class(className, classImp){
function clazz(){
if(typeof this.init == "function"){
this.init.apply(this, arguments);
}
}
classImp.call(clazz.prototype);
window[className] = clazz;
}
* @param {String} className
* @param {Function} classImp
*/
function $class(className, classImp){
function clazz(){
if(typeof this.init == "function"){
this.init.apply(this, arguments);
}
}
classImp.call(clazz.prototype);
window[className] = clazz;
}
寫一個:
$class('Person', function(){
// 私有屬性都定義在這
var age = '';
this.init = function(n, a){
// 共有屬性掛在this上,初始化
this.name = n;
// 私有屬性初始化
age = a;
};
this.getName = function(){
return this.name;
};
this.getAge = function(){
return age;
}
});
// 私有屬性都定義在這
var age = '';
this.init = function(n, a){
// 共有屬性掛在this上,初始化
this.name = n;
// 私有屬性初始化
age = a;
};
this.getName = function(){
return this.name;
};
this.getAge = function(){
return age;
}
});
new一個實例對象:
var p = new Person('jack',23);
console.log(p.name); // jack 共有的可使用點操作符獲取
console.log(p.age); // undefined 私有的不能通過點操作符獲取
console.log(p.getAge()); // 23 私有的age只能通過共有的方法getAge獲取
console.log(p.name); // jack 共有的可使用點操作符獲取
console.log(p.age); // undefined 私有的不能通過點操作符獲取
console.log(p.getAge()); // 23 私有的age只能通過共有的方法getAge獲取
[第1頁][第2頁]
全站熱搜