我正在阅读Nicholas C. Zakas的Web开发人员第三版JavaScript(旧的,我知道),我很难理解为什么静态私有变量/函数首先是静态的。 我理解如果我声明一个带有私有变量/函数的构造函数,它的所有实例都有自己的私有变量/函数,就像在Zakas的一个例子中一样:
function MyObject(){ //private variables and functions var privateVariable = 10; function privateFunction(){ return false; } //privileged methods this.publicMethod = function (){ privateVariable++; return privateFunction(); }; }那么如何将私有变量/函数放在私有作用域中会使变量变为静态? 是因为它们被封闭在一个私人范围内,还是有一些我忽略的东西? 这是Zakas关于静态私有变量的一个例子:
(function(){ //private variables and functions var privateVariable = 10; function privateFunction(){ return false; } //constructor MyObject = function(){ }; //public and privileged methods MyObject.prototype.publicMethod = function(){ privateVariable++; return privateFunction(); }; })();I am reading Nicholas C. Zakas's JavaScript for Web Developers Third Edition (old, I know), and I am having trouble understanding why static private variables/functions are static in the first place. I understand that if I declared a constructor with private variables/functions, all of its instances would have their own private variables/functions, like in one of Zakas's examples:
function MyObject(){ //private variables and functions var privateVariable = 10; function privateFunction(){ return false; } //privileged methods this.publicMethod = function (){ privateVariable++; return privateFunction(); }; }So how would putting private variables/functions in private scopes make the variables static? Is it just because they're enclosed in a private scope, or is there something I'm overlooking? Here's one of Zakas's examples on static private variables:
(function(){ //private variables and functions var privateVariable = 10; function privateFunction(){ return false; } //constructor MyObject = function(){ }; //public and privileged methods MyObject.prototype.publicMethod = function(){ privateVariable++; return privateFunction(); }; })();最满意答案
在第一个示例中,每次调用MyObject privateVariable创建一个新的局部变量privateVariable 。
在第二个示例中, privateVariable是function(){ ... } ,只调用一次,因此只创建一个变量。 这个变量由MyObject.prototype.publicMethod ,然后由MyObject创建的所有对象共享。
In your first example, every time you call MyObject a new local variable privateVariable is created.
In your second example, privateVariable is part of function(){ ... }, which is only called once, so only one variable is ever created. This one variable is used by MyObject.prototype.publicMethod, which is then shared by all objects created through MyObject.
更多推荐
发布评论