Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How can I inherit private properties from parent class

Status
Not open for further replies.

chriscboy

Programmer
Apr 23, 2002
150
0
0
GB
Hi,

I am having problems with trying to understand how I can inherit private properties in subclasses. For example if I have the following :

function MyClass() {

var myprop1 = 1; // Private to MyClass
var myprop2 = 2; // Private to MyClass

this.mymethod1 = function () {
return(1)
}
this.mymethod2 = function () {
return(2)
}

}
function MySubclass() {

this.mysubmethod1 = function () {

myprop = myprop + 1 // causes error 'myprop' is undefined
return(3)
}

}
MySubclass.prototype = new MyClass();
function test() {

var o = new MySubclass();
window.alert(o.mymethod1()) // displays 1
window.alert(o.mysubmethod1());

}

What I was expecting to happen was that MySubclass inherits from MyClass all the properties and methods. The methods are inherited but the private properties myprop1,myprop2 have not which is causing an error when calling the method mysubmethod1.

It appears that myprop1 and myprop2 are private to the class MyClass. The question I have is how do I make myprop1 and myprop2 available to the subclass Mysubclass without making them public properties?

I hope this makes some sense as I come from an OOP background and am struggling with some of the concepts of Javascript!!



 
You're struggling with one of the basic "features" of OOP.
You can't touch the privates.

If there are publicly available setters, you can use them. Private members are set up that way explicitly so that the original class creator trust the values that are in them.

HTH,
Lodlaiden

I'll answer your question, not solve your problem
 
Maybe I misused the word "private".

What I am talking about is having a property of a parent class that can be seen within the subclasses but not be publicly available. In other laguages I have seen this such as Visual FoxPro (known as a protected property) and C# (using the protected access modifier).
 
protected or friend(Java) properties are different. If the memeber is protected, then you just need to inherit the class to be able to access those members.

Note that regular "consumers" still won't have access to the protected attributes.

Lodlaiden

I'll answer your question, not solve your problem
 
Thanks for your reply.

In my original example how would I change it to make myprop1 and myprop2 protected properties?

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top