Reputation: 31
Hi guys is this posibble? calling a function inside a function inside a requirejs module? TIA
define([
'common'
], function(Common) {
return {
func1: function() {
return 'this is function 1';
},
func2 : function (data){
console.log(func1);
}
};
});
Upvotes: 1
Views: 3169
Reputation: 1
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.
Upvotes: -2
Reputation: 3822
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) {
function func1() {
return 'this is function 1';
}
return {
func1: function() {
return func1();
},
func2 : function (data){
console.log(func1);
}
};
});
This way we can access from inside and outside the method func1. For me works very well. Thanks.
Upvotes: 0
Reputation: 110892
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) {
function func1() {
return 'this is function 1';
}
return {
func2 : function (data){
console.log(func1);
}
};
});
But then func1
isn't accessible from outside
Upvotes: 0
Reputation: 1892
Your code as stated won't work. I suggest changing it to something like this:
define([
'common'
], function(Common) {
var exports = {};
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() {
};
return exports;
});
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.
Upvotes: 4