Reputation: 143
please help to run a function that is in a different scope
have the following code:
function a(){
var rrr = 8;
function aim(arg){
console.log('aim' + arg);
console.log(rrr);
}
};
function b(){
a.aim('this is argument');
};
call a.aim ('this is argument');
does not work, the console displays a message
Uncaught ReferenceError: a is not defined
tried to call through apply. also unsuccessfully
Upvotes: 0
Views: 308
Reputation: 18387
using revealing module pattern:
var a = function(){
var rrr = 8;
function aim(arg){
console.log('aim' + arg);
console.log(rrr);
}
return {
aim: aim
}
}();
function b() {
a.aim('test');
}
Upvotes: 4
Reputation: 2018
You need the 2 minor changes:
function a(){
var rrr = 8;
this.aim = function(arg){
console.log('aim' + arg);
console.log(rrr);
}
};
var aa = new a();
function b(){
aa.aim('this is argument');
};
Upvotes: 0
Reputation: 10148
If you want to refer to a
function as an object you need to create it first. Also, aim
should be a property of this function (class)
function a() {
var rrr = 8;
this.aim = function(arg) {
console.log('aim' + arg);
console.log(rrr);
}
};
function b() {
var aa = new a();
aa.aim('this is argument');
}
Upvotes: 0
Reputation: 8139
function a(){
var rrr = 8;
return function aim(arg){
console.log('aim' + arg);
console.log(rrr);
}
};
function b(){
var aim = a();
aim('this is argument');
};
Upvotes: 0