Search code examples
javascriptfunctionvariablesanonymous-functionlanguage-concepts

Javascript - How do I invoke an anonymous method as a variable and access its properties and methods?


I've read that we can invoke an anonymous function as a variable. However I'm trying to do that and in addition to it I want to access its properties and methods. Here is my code

var cooking = function(){
        this.dessert = "Ice Cream";
        this.numberOfPortions = 20;
        this.doubleLunch = function(){this.numberOfPortions = 40;
            document.write(this.numberOfPortions);};
        };

document.write(cooking.dessert);

But I don't get anything. Can you say me what am I doing wrong? Thanks


Solution

  • cooking is a function. When you call it, it defines a number of properties on whatever this is.

    The structure implies that it is intended to be used as a constructor function, so you would create an instance of it using the new keyword.

    Then you can interact with the instance.

    var meal = new cooking();
    document.write(meal.dessert);
    

    NB: Convention dictates that constructor functions (and only constructor functions) should be named starting with a capital first letter, so you should rename it to Cooking.