如何确保持久对象的私人成员真正私密

时间:2014-08-16 18:41:04

标签: javascript private-members

尝试学习如何使用JavaScript创建持久对象,但正如您从下面的示例中可以看到的,可以轻松访问任何Person实例的成员 - 我做错了什么?

function Person(name, age, job){
    "use strict";

    //create the object to return
    var o = new Object();

    //optional: define private variables/functions here
    o.name  = name;
    o.age   = age;
    o.job   = job;

    //attach methods
    o.sayName = function(){
        alert(name);
    };    

    //return the object
    return o;
}

var newGuy = Person("Guy", 21, "Seeker");

newGuy.name; // "Guy" <- Shouldn't this return an error or "undefined"?

3 个答案:

答案 0 :(得分:2)

您获得"Guy",因为您将其设置为name的{​​{1}}属性,然后将o返回到外部,并将其公开。

如果您想要私有变量,可以使用

o

请注意,您不需要创建新的function Person(name, age, job){ "use strict"; // name, age, job are private variables // sayName is a privileged method this.sayName = function(){ alert(name); }; } var newGuy = new Person("Guy", 21, "Seeker"); newGuy.name; // undefined 对象并将其返回,只需使用o运算符调用构造函数,并将公共/特权属性分配给new

我建议阅读道格拉斯·克罗克福德的Private Members in JavaScript

答案 1 :(得分:1)

创建私有属性有很多种不同的方法。他们都想方设法利用变量在函数内局部限定的事实,但可以在函数中捕获。

例如,您可以返回具有私有访问权限的其他对象,而不是返回将显示所有属性的o。这段代码中有一些冗余,但我想让它贴近你的例子:

function person(name, age, job){
     "use strict";
    //optional: define private variables/functions here
    var name  = name;
    var age   = age;
    var job   = job;

   //return the object that uses variable, that are only visible within the function
   return {
        sayName: function(){
                    alert(name);
                    },
        sayJob: function(){
                    alert(job);
                    }
   }
}

var newGuy = person("Guy", 21, "Seeker");

newGuy.sayName();   
newGuy.sayJob();   
alert("undefined: ", newGuy.name); // "Guy" <- Shouldn't this return an error or "undefined"?

答案 2 :(得分:1)

对于一个耐用的物体,道格拉斯克罗克福德建议避免&#34;这个&#34;和&#34;新&#34;共。这就是你想要完成你想要的东西:

var person = function (vals) {
    var that = {}; // create object to avoid constructing with "new" and using "this"

    that.sayName = function () { // bind accessor functions
        return vals.name; // use passed values to ensure privacy
    };

    return that;
};

var guy = person({name: "Guy"}); // avoided use of "new"
alert(guy.name); // undefined as should be
guy.sayName(); // "Guy"

您可以在他的书中找到更多信息:Javascript:The Good Parts(第52页)。我希望这会有所帮助。