首页 > 解决方案 > 如果函数是 JS 中的对象,我们可以在函数内部有方法吗?如果是这样,如何称呼他们?

问题描述

在本例中,greet()函数通过 调用sample.greet()

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

greet()如果这样定义,如何调用内部函数?

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

标签: javascriptnode.jsfunctionobject

解决方案


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();


推荐阅读