質問

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.

役に立ちましたか?

解決

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

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

他のヒント

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.

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.

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

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

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

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

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.

Should work.

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

    }
}

Function definition:

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

Call it as below:

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

// call initValidation function
initValidation()
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top