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

validateスコープinitValidationがあるため、外部には表示されません。

編集:これが解決策の私の提案です。

(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() {
   // code here
   function validate(_block){
     // code here
     console.log(_block);
   }
   return validate;
}

以下のように呼んでください:

initValidation()("hello");
于 2020-02-14T10:25:23.320 に答える
-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 に答える