Javascript,从函数外部调用嵌套函数或从另一个函数内部调用它

问题描述 投票:0回答:1

是否可以从原始函数外部或另一个函数内部调用嵌套在函数内的函数?

因此,在示例中,当第一次调用 func_1 时,它会调用nested_func_1 并返回一个值;

在第二个函数(func_2)中是否可以调用嵌套在func_1内的nested_func_1并返回一个值?

最后是否可以从任何函数外部调用nested_fun_1并返回一个值?

谢谢。

    function func_1(){
        function nested_func_1(a){
            console.log("<br/> NESTED READ");
            a = a * 2;
            return a;
        };
        b = nested_func_1(23);
        return b;
    };
    
    function func_2(){
        // Call function nested_func_1 that is 
        // nested inside func_1 and return value;
        b = nested_func_1(32);
        return b;
    };
    
    a = func_1();
    console.log("AAA "+a);
    
    // CALL THE NESTED FUNCTION - nested_func_1 - 
    // FROM inside func_2 and return result;
    a = func_2();
    console.log("BBB "+a);
    
    // CALL THE NESTED FUNC from 
    // outside both functions;
    b = nested_funct_1(23);
    console.log(b);

javascript function scope
1个回答
0
投票

您可以这样做,以便您可以从外部调用内部函数。

为此,您需要稍微修改代码并将内部函数声明为您自己的函数属性:

function func_1() {
  // custom properties. name_fn.userProperties
  func_1.nested_func_1 = function(a) {
    console.log("<br/> NESTED READ");
    a = a * 2;
    return a;
  }
  return func_1.nested_func_1(23);
}

function func_2() {
  // take properties from func_1
  const b = func_1.nested_func_1(32);
  return b;
}

const a = func_1(); // first call func_1
console.log("AAA " + a);

const b = func_2(); // first call func_2
console.log("BBB " + b);

const c = func_1.nested_func_1(45);
console.log('CCC', c);

为此的一个重要条件是,函数的用户定义属性的可见性仅在函数被调用至少 1 次后才出现。

也就是说,如果在第一次调用 func_1() 之前引用 func_1.nested_func_1,那么我们会得到 undefined

您还可以随时扩展函数的属性

function func_1() {
  console.log('run');
}

func_1();

func_1.newFn = function(d) {
  return d ** 2;
}

console.log(func_1.newFn(5));

这也适用于箭头函数

const arrowFn = () => {
  arrowFn.addFn = (s) => {
    return s * 3;
  }
}

arrowFn();

console.log(arrowFn.addFn(5));

arrowFn.sum = (g) => g + 5;

console.log(arrowFn.sum(5));

© www.soinside.com 2019 - 2024. All rights reserved.