Johan
Johan

Reputation: 35194

Nested functions in "class"

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

Answers (4)

abuduba
abuduba

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

artragis
artragis

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

hvgotcodes
hvgotcodes

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

Try using:

var apple = new Fruits();
apple.Apple();
console.log(apple.getColor());

Upvotes: 1

Related Questions