CHECoder08
CHECoder08

Reputation: 71

If functions are objects in JS, can we have methods inside functions? If so, how to call them?

In this example, the greet() function is invoked through sample.greet().

let sample = {
    greet() {
        console.log("hi")
    }
}

How to invoke the inner greet() function if defined like this?

function sample() {
    function greet() {
        console.log("hi")
    }
}

Upvotes: 0

Views: 71

Answers (2)

jfriend00
jfriend00

Reputation: 707318

Functions declared inside a function body such as the greet() function in your example here:

function sample() {
    function greet() {
        console.log("hi")
    }
}

are private to within the function body and cannot be called from outside of the sample() function scope. You can only call greet() from within the sample() function body unless you somehow assign or return greet after running sample() so you purposely assign greet to some outside variable (which is not present in your example).


Functions are objects so you can create properties on those objects and can then assign a function to a property and can then call it:

function sample() {
    console.log("running sample()");
}

sample.greet = function () {
    console.log("hi")
}

sample.greet();

Upvotes: 2

Jai
Jai

Reputation: 11

You can call the nested function by calling it within the enclosing function. This is because the scope of the nested function is limited to the enclosing function and there is no other way to call it from outside.

function sample() {
    function greet() {
        console.log("hi");
    }
    greet();
}

sample()

Upvotes: 0

Related Questions