Skip to content Skip to sidebar Skip to footer

Calling Function Inside A Function In Requirejs Module Javascript

Hi guys is this posibble? calling a function inside a function inside a requirejs module? TIA define([ 'common' ], function(Common) { return { func1: function() { ret

Solution 1:

Your code as stated won't work. I suggest changing it to something like this:

define([
'common'
], function(Common) {

    varexports = {};

    var func1 = exports.func1 = function() {
        return'this is function 1';
    };

    var func2 = exports.func2 = function (data){
        console.log(func1);
    };

    // A function that is not exported but can be accessed from other code in this module.var privateFunc = function() {
    };

    returnexports;
});

I personally think this style of code is clean and flexible. It is clear which functions are being exported, and they can reference each other using simple, local variable names.

Solution 2:

Lets split a requireJs module in its part to understand what happens:

Let requireJs know that this is a module

define(

Some dependencies

[ 'common'], 

So this is the main part. After all this just a function that is called when loaded. RequireJs save the result of the function and inject it in every module that has this module as dependencies

function(Common) {
  return

So this is what every module get when it require this module

{
    func1: function() {
        return'this is function 1';
    },

    func2 : function (data){
        console.log(func1);

    }
  };

So in your case you return just a simple object with to 2 functions as it members.

What you try to do cant work cause there is no func in the scope, aka the function that returns the object. But a there is member func in your object, so you can call this.func1.

You can also have a function in your function like this:

define([
'common'
], function(Common) {

  functionfunc1() {
    return'this is function 1';
  }
  return {
    func2 : function (data){
        console.log(func1);
    }
  };
});

But then func1 isn't accessible from outside

Solution 3:

Inspired on Andreas Köberle answer I found this work-arround, but Im almost sure there are a better way to do that...

define(function(require) {

  functionfunc1() {
    return'this is function 1';
  }
  return {
    func1: function() {
      returnfunc1();
    },
    func2 : function (data){
        console.log(func1);
    }
  };
});

This way we can access from inside and outside the method func1. For me works very well. Thanks.

Solution 4:

The follwing would work...

console.log(this.func1());

You haven't specified the handle correctly, you have to use this to specify the func1 handle. and i think you were about to call func1() to print 'this is function 1' not just do func1 without paranthesis, as it would print the function definition.

Post a Comment for "Calling Function Inside A Function In Requirejs Module Javascript"