【发布时间】:2016-02-27 17:49:11
【问题描述】:
我发现了类似的问题,但没有一个明确回答这个问题,所以我希望有人能帮我解决这个问题。
关于构造函数,我试图弄清楚变量和函数在默认情况下是公共的还是私有的。
例如,我有这个具有以下属性的示例构造函数:
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'
在我看来,函数和变量默认都是公开的。那正确吗? 或者,如果构造函数中的函数是私有的……它们只能将私有变量作为参数吗?
谢谢。
【问题讨论】:
-
不是 100% 清楚你在问什么。如果您可以访问这些变量和函数,它们肯定是公开的吗?
-
Javascript Variable Scope 可能是一件很难完全理解的事情。 "
In many programming languages, you’ll hear about public and private scope, in JavaScript there is no such thing. We can, however, emulate public and private scope through things like Closures." -
像“…函数和变量都是公共的…”这样的语句让我觉得你对变量和有点困惑属性,或者您的表达方式可能不准确。无论哪种方式,请确保您完全了解其中的区别。
标签: javascript variables object constructor