例子,js面向对象编程之对象的访问控制。
代码:
复制代码 代码示例:
function Cat(name, age){
var name = name;
this.age = age||1;
this.setName = function(sName){
this.name = sName;
}
this.getName = function(){
return this.name;
}
this.setAge = function(nAge){
this.age = nAge;
}
this.getAge = function(){
return this.age;
}
} // www.jb200.com
Cat.prototype.say = function(){
console.log('I am '+this.name+', I am '+this.age);
}
var kk = new Cat('kk');
console.log(kk.name);//undefined @private
kk.setName('deeka');
console.log(kk.getName()); // deeka
kk.setAge(2);
console.log(kk.getAge()); // 2
kk.age = 3;
console.log(kk.age);//3 @public
kk.say(); // I am deeka, I am 3