45

我有以下代码:

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

有什么办法可以在validate()函数外调用initValidation()函数吗?我试过打电话validate(),但我认为它只在父函数中可见。

4

11 回答 11

122

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

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

于 2012-01-11T12:10:59.223 回答
19

希望你正在寻找这样的东西

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

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

这将起作用。

希望这可以解决您的问题。

于 2012-01-11T12:25:05.673 回答
7

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

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

    return validate(someVar);
}

validateinitValidation由于它的作用域,它对任何外部的东西都是不可见的。

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

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

    function initValidation()
    {
        // irrelevant code here

        return validate(someVar);
    }

    function otherFunctions() {
        // ...
    }

    // initValidation = function
}());

// initValidation = undefined

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

于 2012-01-11T10:42:23.943 回答
2

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

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

initValidation()();
于 2017-10-05T14:46:13.283 回答
1

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

"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);
于 2016-06-15T14:18:17.770 回答
1

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

请注意,在任何地方,都应该考虑一个更好的设计决策,而不是一些会在以后让您反悔的变通办法

如何使用函数表达式而不是函数语句并利用全局范围

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

于 2019-06-11T05:55:53.203 回答
1

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

Var Store;
Function blah() {

    Function needed() {
        #
    }

   Store = needed;
}
于 2020-10-03T22:16:22.860 回答
0

作为 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() 之间完全共享,并且对外界完全不可见。

于 2021-01-03T15:04:05.760 回答
-1

应该管用。

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

    }
}
于 2012-01-11T10:42:39.827 回答
-1
function initValidation()
{
   
    function validate(_block){
        console.log(_block)
        // code here
    }
    // you have to call nested function
    validate("Its Work")
}

// call initValidation function
initValidation()
于 2020-12-21T15:13:51.380 回答
-1

函数定义:

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

如下调用它:

initValidation()("hello");
于 2020-02-14T10:25:23.320 回答