尝试学习如何使用 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"?
最佳答案
您得到 "Guy"
因为您将其设置为 o
的 name
属性,然后返回 o
对外公开。
如果你想要私有(private)变量,可以使用
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
运算符调用构造函数并将公共(public)/特权属性分配给 这个
。
我建议阅读Private Members in JavaScript ,作者:道格拉斯·克罗克福德。
关于javascript - 如何确保持久对象的私有(private)成员是真正私有(private)的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25342743/