一、使用构造函数获得私有属性:
function Gadget(){
var name = 'iPod';
this.getName = function(){
return name;
};
}; var toy = new Gadget();
console.log(toy.name);//undefined
console.log(toy.getName());//iPod
注意,当返回变量为数组或对象时,私有性失效:
function Gadget(){
var specs = {
width: 400,
height: 500
};
this.getSpecs = function(){
return specs;
};
}; var toy = new Gadget();
var specs = toy.getSpecs();
specs.color = 'black';
console.log(toy.getSpecs());//{ width: 400, height: 500, color: 'black' }
二、使用对象字面量
var myobj = (function(){
var name = 'wqh';
return {
getName: function(){
return name;
}
}
})();
console.log(myobj.name);//undefined
console.log(myobj.getName());//wqh
三、共享的私有属性:prototype中
function Gadget(){
var name = 'iPod';
this.getName = function(){
return name;
};
}; Gadget.prototype = (function(){
var browser = 'Webkit';
return {
getBrowser: function(){
return browser;
}
};
})(); var toy = new Gadget(); console.log(toy.name);//undefined
console.log(toy.getName());//iPod
console.log(toy.browser);//undefined
console.log(toy.getBrowser());//Webkit
注:JavaScript模式P94-98