JavaScript中的私有属性

一、使用构造函数获得私有属性:

 1 function Gadget(){
 2     var name = 'iPod';
 3     this.getName = function(){
 4         return name;
 5     };
 6 };
 7 
 8 var toy = new Gadget();
 9 console.log(toy.name);//undefined
10 console.log(toy.getName());//iPod

注意,当返回变量为数组或对象时,私有性失效:

function Gadget(){
    var specs = {
         400,
        height: 500
    };
    this.getSpecs = function(){
        return specs;
    };
};

var toy = new Gadget();
var specs = toy.getSpecs();
specs.color = 'black';
console.log(toy.getSpecs());//{  400, height: 500, color: 'black' }

二、使用对象字面量

 1 var myobj = (function(){
 2     var name = 'wqh';
 3     return {
 4         getName: function(){
 5             return name;
 6         }
 7     }
 8 })();
 9 console.log(myobj.name);//undefined
10 console.log(myobj.getName());//wqh

三、共享的私有属性:prototype中

 1 function Gadget(){
 2     var name = 'iPod';
 3     this.getName = function(){
 4         return name;
 5     };
 6 };
 7 
 8 Gadget.prototype = (function(){
 9     var browser = 'Webkit';
10     return {
11         getBrowser: function(){
12             return browser;
13         }
14     };
15 })();
16 
17 var toy = new Gadget();
18 
19 console.log(toy.name);//undefined
20 console.log(toy.getName());//iPod
21 console.log(toy.browser);//undefined
22 console.log(toy.getBrowser());//Webkit

注:JavaScript模式P94-98

原文地址:https://www.cnblogs.com/redking-fighting/p/6250317.html