JavaScript 调用嵌套函数

发布于 2024-12-26 18:12:08 字数 284 浏览 2 评论 0原文

我有以下代码:

function initValidation()
{
    // irrelevant code here
    function validate(_block){
        // code here
    }
}

有什么方法可以在 initValidation() 函数之外调用 validate() 函数吗?我尝试过调用 validate() 但我认为它仅在父函数中可见。

I have the following piece of code:

function initValidation()
{
    // irrelevant code here
    function validate(_block){
        // code here
    }
}

Is there any way I can call the validate() function outside the initValidation() function? I've tried calling validate() but I think it's only visible inside the parent function.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

浴红衣 2025-01-02 18:12:08
    function initValidation()
    {
        // irrelevant code here
        function validate(_block){
            console.log( "test", _block );
        }
    
        initValidation.validate = validate;
    }

    initValidation();
    initValidation.validate( "hello" );
    //test hello

    function initValidation()
    {
        // irrelevant code here
        function validate(_block){
            console.log( "test", _block );
        }
    
        initValidation.validate = validate;
    }

    initValidation();
    initValidation.validate( "hello" );
    //test hello

木槿暧夏七纪年 2025-01-02 18:12:08

希望您正在寻找这样的东西,

function initValidation()
{
    // irrelevant code here
    this.validate = function(_block){
        // code here
    }
}

var fCall = new initValidation()
fCall.validate(param);

这会起作用。

希望这能解决您的问题。

Hope that you are looking for something like this

function initValidation()
{
    // irrelevant code here
    this.validate = function(_block){
        // code here
    }
}

var fCall = new initValidation()
fCall.validate(param);

This will work.

Hope this addresses your problem.

我的奇迹 2025-01-02 18:12:08

您可以从 initValidation 中调用 validate。像这样。

function initValidation()
{
    // irrelevant code here
    function validate(_block){
        // code here
    }

    return validate(someVar);
}

validate 对于 initValidation 之外的任何内容都是不可见的,因为它的 范围

编辑:这是我的解决方案建议。

(function() {
    function validate(_block){
        // code here
    }

    function initValidation()
    {
        // irrelevant code here

        return validate(someVar);
    }

    function otherFunctions() {
        // ...
    }

    // initValidation = function
}());

// initValidation = undefined

您的所有函数都将对函数包装器之外的任何内容隐藏,但都可以互相看到。

You can call validate from within initValidation. Like this.

function initValidation()
{
    // irrelevant code here
    function validate(_block){
        // code here
    }

    return validate(someVar);
}

validate is not visible to anything outside of initValidation because of its scope.

Edit: Here's my suggestion of a solution.

(function() {
    function validate(_block){
        // code here
    }

    function initValidation()
    {
        // irrelevant code here

        return validate(someVar);
    }

    function otherFunctions() {
        // ...
    }

    // initValidation = function
}());

// initValidation = undefined

All of your functions will be hidden to anything outside the function wrapper but can all see each other.

狠疯拽 2025-01-02 18:12:08

该调用将返回函数语句,即函数验证。
所以你可以在第一次调用后直接调用。

function initValidation() {
  // irrelevant code here
  return function validate(_block) {
    // code here
  }
}

initValidation()();

This invocation will return function statement, which is function validate.
So you can invoke directly after the first invocation.

function initValidation() {
  // irrelevant code here
  return function validate(_block) {
    // code here
  }
}

initValidation()();
吹泡泡o 2025-01-02 18:12:08

我知道这是一篇旧文章,但如果您希望创建一组您希望使用的实例来重用代码,您可以执行以下操作:

"use strict";
// this is derived from several posts here on SO and ultimately John Resig
function makeClassStrict() {
  var isInternal, instance;
  var constructor = function(args) {
    if (this instanceof constructor) {
      if (typeof this.init == "function") {
        this.init.apply(this, isInternal ? args : arguments);
      }
    } else {
      isInternal = true;
      instance = new constructor(arguments);
      isInternal = false;
      return instance;
    }
  };
  return constructor;
}
var MyClass = makeClassStrict();// create "class"
MyClass.prototype.init = function(employeeName, isWorking) {
  var defaultName = 'notbob';
  this.name = employeeName ? employeeName : defaultName;
  this.working = !!isWorking;
  this.internalValidate = function() {
    return {
      "check": this.working,
      "who": this.name
    };
  };
};
MyClass.prototype.getName = function() {
  return this.name
};
MyClass.prototype.protoValidate = function() {
return {
      "check": this.working,
      "who": this.name
    };
};
var instanceBob = MyClass("Bob", true);// create instance
var instanceFred = MyClass("Fred", false);// create instance
var mything = instanceFred.internalValidate();// call instance function
console.log(mything.check + ":" + mything.who);
var myBobthing = instanceBob.protoValidate();
console.log(myBobthing.check + ":" + myBobthing.who);

I know this is an old post but if you wish to create a set of instances that you wish to work with that reuse the code you could do something like this:

"use strict";
// this is derived from several posts here on SO and ultimately John Resig
function makeClassStrict() {
  var isInternal, instance;
  var constructor = function(args) {
    if (this instanceof constructor) {
      if (typeof this.init == "function") {
        this.init.apply(this, isInternal ? args : arguments);
      }
    } else {
      isInternal = true;
      instance = new constructor(arguments);
      isInternal = false;
      return instance;
    }
  };
  return constructor;
}
var MyClass = makeClassStrict();// create "class"
MyClass.prototype.init = function(employeeName, isWorking) {
  var defaultName = 'notbob';
  this.name = employeeName ? employeeName : defaultName;
  this.working = !!isWorking;
  this.internalValidate = function() {
    return {
      "check": this.working,
      "who": this.name
    };
  };
};
MyClass.prototype.getName = function() {
  return this.name
};
MyClass.prototype.protoValidate = function() {
return {
      "check": this.working,
      "who": this.name
    };
};
var instanceBob = MyClass("Bob", true);// create instance
var instanceFred = MyClass("Fred", false);// create instance
var mything = instanceFred.internalValidate();// call instance function
console.log(mything.check + ":" + mything.who);
var myBobthing = instanceBob.protoValidate();
console.log(myBobthing.check + ":" + myBobthing.who);
泪是无色的血 2025-01-02 18:12:08

我知道这个线程已经存在很长一段时间了,但我想我也应该留下 0.02$ 来讨论如何从其范围之外调用内部函数(可能会让某人受益)。

请注意,在任何地方,都应该考虑更好的设计决策,而不是一些会在以后给您带来麻烦的黑客解决方案

如何使用 函数表达式 而不是 < a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions#The_function_declaration_(function_statement)" rel="nofollow noreferrer">函数语句并利用全局范围。

      var innerFn;
    
      function outerFn() {
        innerFn = function(number) {
          return number ** 2;
        }
      }
    
      outerFn();
      console.log(innerFn(5));

      // if there's more complex code around and you could write this defensively

      if (typeof innerFn !== 'undefined') {
        console.log(`we are squaring the number 5 and the result is: ${innerFn(5)}`);
      } else {
        console.log('function is undefined');
      }

或者,您可以使用闭包

function outer() {
  // initialize some parameters, do a bunch of stuff
  let x = 5, y = 10;

  function inner() {
    // keeps references alive to all arguments and parameters in all scopes it references
    return `The arithmetic mean of the 2 numbers is: ${(x + y) / 2}`;
  }
  
  return inner;
}

innerFn = outer(); // get a reference to the inner function which you can call from outside
console.log(innerFn());

I know this thread's been here for quite some time but I thought I'd also leave my 0.02$ on how to call inner functions from outside their scope (might benefit somebody).

Note that in any place, a better design decision should be taken into consideration rather than some hackish workaround which will bite you back later.

How about using function expressions instead of function statements and making use of the global scope.

      var innerFn;
    
      function outerFn() {
        innerFn = function(number) {
          return number ** 2;
        }
      }
    
      outerFn();
      console.log(innerFn(5));

      // if there's more complex code around and you could write this defensively

      if (typeof innerFn !== 'undefined') {
        console.log(`we are squaring the number 5 and the result is: ${innerFn(5)}`);
      } else {
        console.log('function is undefined');
      }

Or, you can make use of closures:

function outer() {
  // initialize some parameters, do a bunch of stuff
  let x = 5, y = 10;

  function inner() {
    // keeps references alive to all arguments and parameters in all scopes it references
    return `The arithmetic mean of the 2 numbers is: ${(x + y) / 2}`;
  }
  
  return inner;
}

innerFn = outer(); // get a reference to the inner function which you can call from outside
console.log(innerFn());

暮年慕年 2025-01-02 18:12:08

在父函数外部创建一个变量,然后在父函数中将所需的函数存储在该变量中。

Var Store;
Function blah() {

    Function needed() {
        #
    }

   Store = needed;
}

Create a variable outside the parent function, then in the parent function store your required function in the variable.

Var Store;
Function blah() {

    Function needed() {
        #
    }

   Store = needed;
}
一笑百媚生 2025-01-02 18:12:08

作为 Esailija 答案的一个微小变化,我这样做了:

function createTree(somearg) {
    function validate(_block) {
        console.log( "test", _block );
    }
    if (somearg==="validate") { return validate; } // for addNodes

    // normal invocation code here
    validate(somearg);
}

function addNodes() {
    const validate = createTree("validate");
    //...
    validate( "hello" );
}

createTree("create");
addNodes();
//validate("illegal");

所以 validate() 现在在 createTree() 和 addNodes() 之间完美共享,并且对外界完全不可见。

As a minor variation of Esailija's answer, I did this:

function createTree(somearg) {
    function validate(_block) {
        console.log( "test", _block );
    }
    if (somearg==="validate") { return validate; } // for addNodes

    // normal invocation code here
    validate(somearg);
}

function addNodes() {
    const validate = createTree("validate");
    //...
    validate( "hello" );
}

createTree("create");
addNodes();
//validate("illegal");

so validate() is now perfectly shared between createTree() and addNodes(), and perfectly invisible to the outside world.

逆光下的微笑 2025-01-02 18:12:08

函数定义:

function initValidation() {
   // code here
   function validate(_block){
     // code here
     console.log(_block);
   }
   return validate;
}

调用如下:

initValidation()("hello");

Function definition:

function initValidation() {
   // code here
   function validate(_block){
     // code here
     console.log(_block);
   }
   return validate;
}

Call it as below:

initValidation()("hello");
仙气飘飘 2025-01-02 18:12:08

应该有效。

function initValudation() {
    validate();
    function validate() {

    }
}

Should work.

function initValudation() {
    validate();
    function validate() {

    }
}
暗地喜欢 2025-01-02 18:12:08
function initValidation()
{
   
    function validate(_block){
        console.log(_block)
        // code here
    }
    // you have to call nested function
    validate("Its Work")
}

// call initValidation function
initValidation()
function initValidation()
{
   
    function validate(_block){
        console.log(_block)
        // code here
    }
    // you have to call nested function
    validate("Its Work")
}

// call initValidation function
initValidation()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文