Reputation: 35194
function Fruits() {
this.Banana = function() {
this.getColor = function(){
return 'yellow';
};
};
this.Apple= function() {
this.getColor = function(){
return 'red';
};
};
}
var apple = new Fruits.Apple();
console.log(apple.getColor());
This doesnt work. What did i miss here? Is this the wrong approach on a "class" with nested methods?
Thanks
Upvotes: 0
Views: 59
Reputation: 5042
Some curiosity:
var a = new new Fruits().Apple
Btw. Maybe you wanted to create a something like static class?
var Fruits = {
Apple:function() {
this.getColor = function(){
return 'red';
};
},
Banana: function() {
this.getColor = function(){
return 'yellow';
};
}
}
Then it would work.
var apple = new Fruits.Apple();
console.log(apple.getColor());
Upvotes: 1
Reputation: 3713
It is the very difference between static properties and instance properties. As you declared Apple as an instance property of Fruits, you have to instanciate a Fruit to be allowed to instanciate an apple, and the cronstructor of Apple will be a method of Fruit. If you want static class you have to do
function Fruits() {
}; Fruits.Apple= function() {
this.getColor = function(){
return 'red';
};
};
Upvotes: 1
Reputation: 120198
You need to instantiate Fruits first. From my console...
var f = new Fruits()
undefined
new f.Apple()
Fruits.Apple
new f.Apple().getColor()
"red"
Upvotes: 1
Reputation: 2664
Try using:
var apple = new Fruits();
apple.Apple();
console.log(apple.getColor());
Upvotes: 1