我发现了类似的问题,但没有人明确回答这个问题,所以我希望有人可以帮我解决这个问题。
关于构造函数,我试图计算变量和函数默认情况下是公共还是私有。
例如,我有这个样本构造函数具有以下属性:
function Obj() {
this.type = 'object';
this.questions = 27;
this.print = function() {
console.log('hello world');
}
}
我可以这样称呼这些属性:
var box = new Obj();
box.type; // 'object'
box.print(); // 'hello world'
在我看来,默认情况下函数和变量都是公共的。是对的吗? 或者,如果构造函数内的函数是私有的......它们只能将私有变量作为参数吗?
谢谢。
答案 0 :(得分:6)
Javascript中的实例上的所有属性(使用this.property = xxx
分配的内容)都是公开的 - 无论它们是在构造函数中还是在其他位置分配。
如果你使用Object.defineProperty()
,某个属性可能是只读的,或者可能是getter或setter,但它们对外界都是可见的。
Javascript没有内置语言功能,用于"私有"属性。您可以在构造函数中将局部变量或局部函数用作私有,但它们仅可用于构造函数中定义的代码或方法。
所以,在你的例子中:
function Obj() {
this.type = 'object';
this.questions = 27;
this.print = function() {
console.log('hello world');
}
}
所有属性type
,questions
和print
均可公开访问。
一种创造"私人"方法是在构造函数中定义一个局部函数,如下所示:
function Obj() {
var self = this;
// this is private - can only be called from within code defined in the constructor
function doSomethingPrivate(x) {
console.log(self.type);
}
this.type = 'object';
this.questions = 27;
this.print = function(x) {
doSomethingPrivate(x);
}
}
这是使用构造函数闭包创建私有访问的更常见参考之一:http://javascript.crockford.com/private.html。