0
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

4 Answers 4

1

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());
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, this will be perfect. Thanks!
1

Try using:

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

Comments

1

You need to instantiate Fruits first. From my console...

var f = new Fruits()
undefined
new f.Apple()
Fruits.Apple
new f.Apple().getColor()
"red"

Comments

1

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';
    };

}; 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.