Reputation: 3191
I'm new to javascript, so some of the existing answers on StackOverflow confused me.
If I have a static class inside of a dynamic class (like below). How can I access variables inside the dynamic class?
function ListItem() = {
var myItem = function() { return "something" };
...
ItemDropdown = function(){
show : function (){
//Want to access the ListItem's myItem here
alert(super.myItem() + "dropdown menu");
}
}
}
var foo = new ListItem();
foo.ItemDropdown.show();
Upvotes: 1
Views: 134
Reputation: 20235
If you want ItemDropdown
to be a method of ListItem
, you need to declare it using this
.
this.ItemDropdown = {
With the way you have myItem
defined, you can just call it by itself.
alert(myItem() + "dropdown menu");
You also have a couple syntax errors:
function ListItem() = {
// Should be
function ListItem() {
and
ItemDropdown = function(){
// Should be
this.ItemDropdown = {
So, you end up with this:
function ListItem() {
var myItem = function() { return "something" };
this.ItemDropdown = {
show : function (){
alert(myItem() + "dropdown menu");
}
}
}
Upvotes: 2
Reputation: 82594
use this
function ListItem() {
var myItem = function() { return "something" };
...
this.ItemDropdown = {
show : function (){
//Want to access the ListItem's myItem here
alert(myItem() + "dropdown menu"); // no super in javascript
}
}
}
I've fixed to errors:
Upvotes: 0
Reputation: 17765
First of all, Javascript is not class based inheritance, it is prototype based inheritance. You need to use terms such as "function constructor". If you are coming from a "traditional" class based inheritance language, then check this out.
This being said, if you want this to work:
var foo = new ListItem();
foo.ItemDropdown.show();
Then ItemDropdown
must be a property of the ListItem
definition (eg: function constructor) - which means you need to use this
.
Upvotes: 1