Reputation: 71
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
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
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