Inheritance and private variables

B

Björn Langhof

Hallo.

Is it possible to set private variables "var c=..." in the parent class
and use them in the inherited class?

My parent class looks like this:
function parentclass(){
var txt = 'foo';
}

My child class is this:
function childclass(){
var p = document.getElementById('myElement');
p.addEventListener('click', action, true);
function action(){ alert(txt);}
}
childclass.prototype = new parentclass();

Now the problem is: The variable txt in alert is not defined.
Well a workaround is to set the variable as public in the parent class
this.txt = foo;
and copy the variable in the child class into a private variable
var txt = this.txt;
because this.txt doesn't work in the alert-call.

Do you have any idea how to solve this? Or is my total approach wrong?

Thanks for your help in advance.

Greetings,
Björn


The full example:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>

<head>
</head>
<script type="text/javascript">
function parentclass(){
// this.txt = 'foo'; // Workaround
var txt = 'foo';
}

function childclass(){
// var txt = this.txt; // Workaround
var p = document.getElementById('myElement');
p.addEventListener('click', action, true);
function action(){ alert(txt);}
}
childclass.prototype = new parentclass();

function init(){var child = new childclass();}

</script>

<body onLoad="init()">
<p id="myElement">Text</p>
</body>
</html>
 
D

dipiamaze

you could do the following:

function childclass(){
// var txt = this.txt; // Workaround
var p = document.getElementById('myElement');
p.addEventListener('click', action, true);
var me = this;
function action(){ alert(me.txt);}
}

Now the action closure has a reference "me" to the actual instance of
childclass.

dip
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top