473,386 Members | 1,733 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Private instance members

Is it possible to have private instance members in a javascript class?

function myObject() {
var private = 1;

this.getPrivate = function() {
return private;
}

this.incrementPrivate = function() {
private += 1;
}
}

var a = new myObject();
var b = new myObject();
a.incrementPrivate();

When I test the example above, calling b.getPrivate() returns 2, so it
appears that private members can only be static? I know that it is
possible to use "this.private" to achieve the intended functionality
with a public member but would prefer to make the variable "private"
inaccessible to code outside the class.
Jul 20 '05 #1
12 2622


Will wrote:
Is it possible to have private instance members in a javascript class?

function myObject() {
var private = 1;

this.getPrivate = function() {
return private;
}

this.incrementPrivate = function() {
private += 1;
}
}

var a = new myObject();
var b = new myObject();
a.incrementPrivate();

When I test the example above, calling b.getPrivate() returns 2, so it
appears that private members can only be static? I know that it is
possible to use "this.private" to achieve the intended functionality
with a public member but would prefer to make the variable "private"
inaccessible to code outside the class.


Which browser are you using?
private is a reserved word I think therefore Netscape gives an error and
shouldn't yield a result at all.
And if I try

function myObject() {
var private = 1;

this.getPrivate = function() {
return private;
}

this.incrementPrivate = function() {
private += 1;
}
}

var a = new myObject();
var b = new myObject();
a.incrementPrivate();
alert(b.getPrivate())

with IE6 it alerts 1.
--

Martin Honnen
http://JavaScript.FAQTs.com/

Jul 20 '05 #2
> function myObject() {
var private = 1;

this.getPrivate = function() {
return private;
}

this.incrementPrivate = function() {
private += 1;
}
}

var a = new myObject();
var b = new myObject();
a.incrementPrivate();

When I test the example above, calling b.getPrivate() returns 2, so it
appears that private members can only be static? I know that it is
possible to use "this.private" to achieve the intended functionality
with a public member but would prefer to make the variable "private"
inaccessible to code outside the class.


I ran it through JSLINT and it found that you are misusing 'private', a
reserved word.

http://www.crockford.com/javascript/lint.html
Jul 20 '05 #3
Sorry for the confusion. The previous example was thrown together for
demonstration purposes and I should have remembered about "private"
being a reserved word.

The problem actually relates to private instance variables with a
prototyped class. For example:

function myObject() {
var i = 1;
this.ret = function() {return i;}
this.increment = function() {i += 1;}
}

myObject2.prototype = new myObject();
function myObject2() {}

var a = new myObject2();
var b = new myObject2();
a.increment();
alert(b.ret())

In this example,b.ret() returns 2 where I would expect 1. It appears
as though both objects "a" and "b" share an instance of the prototyped
class "myObject()", because the methods of each object alter the value
of the private variable for both.

I find this behaviour a bit odd and wonder if there is either
something I am missing or a workaround to enable the two objects to
maintain the variable "i" independently of one another whilst keeping
"i" as a private variable.
Jul 20 '05 #4


Will wrote:
Sorry for the confusion. The previous example was thrown together for
demonstration purposes and I should have remembered about "private"
being a reserved word.

The problem actually relates to private instance variables with a
prototyped class. For example:

function myObject() {
var i = 1;
this.ret = function() {return i;}
this.increment = function() {i += 1;}
}

myObject2.prototype = new myObject();
function myObject2() {}

var a = new myObject2();
var b = new myObject2();
a.increment();
alert(b.ret())

In this example,b.ret() returns 2 where I would expect 1. It appears
as though both objects "a" and "b" share an instance of the prototyped
class "myObject()", because the methods of each object alter the value
of the private variable for both.

I find this behaviour a bit odd and wonder if there is either
something I am missing or a workaround to enable the two objects to
maintain the variable "i" independently of one another whilst keeping
"i" as a private variable.


The beahviour is not odd, and your explanation is quite right, the two
objects share an "instance of myObject" as their prototype, that is how
prototyping works, an object is created and serves as the prototype.
Whoever has sold this approach of "private instance members" should have
told you that it breaks with prototypes being introduced.
--

Martin Honnen
http://JavaScript.FAQTs.com/

Jul 20 '05 #5
Please to report that I have now found the answer, thanks to this excellent article:

http://www.pbwizard.com/Articles/class_inheritance.htm

Well worth a read.
Jul 20 '05 #6
"Martin Honnen" <ma*******@yahoo.de> wrote in message
news:3f********@olaf.komtel.net...
<snip>
Whoever has sold this approach of "private instance members"
should have told you that it breaks with prototypes being
introduced.


As Douglas Crockford appears to be responsible for inventing the
technique for emulating private instance members in JavaScript (though I
can't see that as "selling") it is probably not surprising that he has
also published pages on alternative approaches to inheritance, some of
which would address this problem.

As the emulation of private instance members is achieved by forming a
closure, in which the private members are stored, by assigning inner
functions of the constructor to public members of the object instance,
the technique results in each object instance being associated with a
closure. Assigning an super class object instance to the prototype
results in only one closure being associated with all instances of the
subclass, but the subclass instances do not each have a closure of their
own to hold any private instance members that they may want. Attaching a
closure to the prototype is an action that can be exploited as one of
the methods of emulating private static members (the other (and perhaps
preferable) method being to associate a closure with the class
constructor).

For instances of a class to inherit private instance member
functionality from a superclass they would have to explicitly create the
same closure as the superclass, which could be achieved by using the
Function.prototype.apply or call methods to apply the superclass
constructor to the - this - object (probably within the subclass
constructor).

Richard.
Jul 20 '05 #7


Richard Cornford wrote:
For instances of a class to inherit private instance member
functionality from a superclass they would have to explicitly create the
same closure as the superclass, which could be achieved by using the
Function.prototype.apply or call methods to apply the superclass
constructor to the - this - object (probably within the subclass
constructor).


Sure, but apply/call only made it into IE5.5/JScript 5.5 and are not
supported in earlier JScript versions so in my view can't be relied on
currently on Web pages.

--

Martin Honnen
http://JavaScript.FAQTs.com/

Jul 20 '05 #8
"Martin Honnen" <ma*******@yahoo.de> wrote in message
news:3f********@olaf.komtel.net...
<snip>
... , which could be achieved by using the
Function.prototype.apply or call methods to apply the
superclass constructor to the - this - object (probably
within the subclass constructor).


Sure, but apply/call only made it into IE5.5/JScript 5.5 and
are not supported in earlier JScript versions so in my view
can't be relied on currently on Web pages.


True, they are missing from IE 4 & 5.0, but they can each be emulated
when absent, and that addresses web page reliability issues (obviously
at the cost of maybe 20 extra lines of code).

On the other hand I have not seen much need for inheritance in a web
page environment, they are just not that complicated. Where I do see
inheritance being a significant consideration is with the implementation
of business logic in an ASP/IIS environment. But then the JScript
version is known so reliability is not an issue.

Richard.
Jul 20 '05 #9
Will wrote:
Is it possible to have private instance members in a javascript class?
No, and unless you are talking about JavaScript 2.0 there are no classes
in JavaScript. The below declares and defines a constructor function
for a prototype object and therefore that object itself.
function myObject() {
var private = 1;

this.getPrivate = function() {
return private;
}

this.incrementPrivate = function() {
private += 1;
}
}

var a = new myObject();
var b = new myObject();
a.incrementPrivate();


The `new' operator creates a new object based on the prototype
object (inheriting its properties) and returns a reference to
that object which you assign to variables here, making their
identifiers object references on which the lookup operator `.'
can be applied.

Since in prototype-based languages like JavaScript 1.x every
object is an `instance', it is better to avoid that term there
to avoid confusion.

See
http://devedge.netscape.com/library/...2.html#1008342
PointedEars
Jul 20 '05 #10
> > Is it possible to have private instance members in a javascript class?

No, and unless you are talking about JavaScript 2.0 there are no classes
in JavaScript. The below declares and defines a constructor function
for a prototype object and therefore that object itself.


Yes, actually. The problem with the example below is that it misuses 'private',
a reserved word unfortunately. If you replaced it with a non-reserved word, then
it would act as a private instance variable that can only be access through the
priviledged functions.
function myObject() {
var private = 1;

this.getPrivate = function() {
return private;
}

this.incrementPrivate = function() {
private += 1;
}
}

var a = new myObject();
var b = new myObject();
a.incrementPrivate();


See http://www.crockford.com/javascript/private.html

Jul 20 '05 #11
Will wrote:
Please to report that I have now found the answer, thanks to this
excellent article:
You are wrong.
http://www.pbwizard.com/Articles/class_inheritance.htm

Well worth a read.
The information provided in this document is awfully wrong, most
certainly based on a lack of knowledge about prototype-based languages
in general and especially JavaScript 1.x. As for example:
[...]
Data Members

Note: Data members are variables (including object references) and
functions.

Within an object there are two types of data members supported by
JavaScript. Public and private. Public data members are those
properties that we assign to the this object within the constructor.


There is no distinction between private and public properties in
JavaScript 1.x and where a property is defined does not change its
access restrictions because there are simply *none*.

function Foo()
{
this.x = 42;
this.blurb = function() { return false; };
}

var b = new Foo();
b.y = 23;
b.haha = function() { return true; };
Foo.x = -1;
alert(x);
alert(y);
alert(Foo.x);
alert(Foo.blurb());
alert(b.blurb());
alert(b.haha());
PointedEars
Jul 20 '05 #12
Douglas Crockford wrote:
[...] The problem with the example below is that it misuses 'private',
a reserved word unfortunately. If you replaced it with a non-reserved word, then
it would act as a private instance variable that can only be access through the
s/as/like/
priviledged functions.


ACK. Although understandable, I find that
way of coding somehow strange, though.
> function myObject() {
> var private = 1;
> [...]


PointedEars
Jul 20 '05 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

34
by: Andy | last post by:
1) Is there any use of defining a class with a single constructor declared in private scope? I am not asking a about private copy constructors to always force pass/return by reference. 2) Is...
5
by: Sandeep | last post by:
Hi, In the following code, I wonder how a private member of the class is being accessed. The code compiles well in Visual Studio 6.0. class Sample { private: int x; public:
4
by: baumann | last post by:
hi all, according the private / protected access control, - private; that is, its name can be used only by members and friends of the class in which it is declared. - protected; that is,...
1
by: Andrew Poulos | last post by:
I having some trouble understanding how to make functions private I have created an instance of an object using a constructor function and there are 4 prototypes: Comm = function() { //blah...
2
by: Christoph Boget | last post by:
Let's take the following class: class MyClass { private int privateVar; public int PublicVar { get { return privateVar; } } public MyClass() {}
10
by: Abelardo Vacca | last post by:
Hi, The title sums up the question pretty much. I would like to access all private members of a class including the private members of its base classes.( I already have the ReflectionPermission )...
6
by: Ken Varn | last post by:
I have an ASP.NET application that is calling a custom class that is trying to parse all of the members of my Page object using Type.GetMembers(). The problem that I am having is that private...
12
by: tobias.sturn | last post by:
Hi! My prof told me always to make my members private or protected cause its standard to write setter and getter methodes.. Is that in your opinion correct? Cause I dont see any adventages to...
11
by: Yarco | last post by:
For example: <?php class Test { private $name = 'yarco'; } $p = new ReflectionPropery('Test', 'name'); print $p->getValue();
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.