Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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

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

Problem

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 ?

Problem courtesy of: user2644806

Solution

In JavaScript, a variable declared without the "var" keyword has global scope. In the browser this is achieved by attaching the variable to the window object (not sure how it works in Node). If you would like a Private Variable Accessible to your object, try a closure around the object constructor and prototype declaration.

Solution courtesy of: William Neely

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

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

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×