简体   繁体   English

是否可以在node.js原型定义的函数中访问私有变量?

[英]Private variable accessible in node.js prototype-defined function?

Consider the following code snippet: 考虑以下代码片段:

function C1() {
    // private variable in the constructor
    a = 1;
}

C1.prototype.f1 = function() {
console.log( "a=" +  a );
}

C1.prototype.f2 = function() {
    a = 2;
    process.nextTick( this.f1 );
}

o = new C1();
o.f1();
o.f2();

The output observed is: 观察到的输出是:

a=1
a=2

I thought private variables aren't accessible outside of the Constructor function ? 我以为在构造函数之外无法访问私有变量?

In JavaScript, a variable declared without the "var" keyword has global scope. 在JavaScript中,声明为不带“ var”关键字的变量具有全局作用域。 In the browser this is achieved by attaching the variable to the window object (not sure how it works in Node). 在浏览器中,这是通过将变量附加到窗口对象来实现的(不确定其在Node中的工作方式)。 If you would like a private variable accessible to your object, try a closure around the object constructor and prototype declaration. 如果您希望对象可以访问一个私有变量,请尝试围绕对象构造函数和原型声明进行闭包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM