为什么JavaScript中的静态私有变量是静态的?(Why are static private variables in JavaScript static?)

编程入门 行业动态 更新时间:2024-10-18 18:28:04
为什么JavaScript中的静态私有变量是静态的?(Why are static private variables in JavaScript static?)

我正在阅读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.

更多推荐

本文发布于:2023-08-01 11:50:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1358022.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:静态   变量   JavaScript   variables   private

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!