Javascript : Access Return Of Other Function
Is it possible that by calling one function I can get the return of function called inside? function f1(...){ f2(...); } function f2(...){ return 123; } In other words by c
Solution 1:
You want to return the returned value
function f1(...){
return f2(...);
}
function f2(...){
return 123;
}
alert(f1());//123
Solution 2:
If you want to save the return value use this:
functionf1(...){
var f2return = f2(...);
}
functionf2(...){
return123;
}
If you want to return it directly use @Travis Js code.
I would propose to save the return value into a variable for further processing, otherwise I would just call f2 directly. Keep in mind that any return statement exits the current function.
Solution 3:
Why not?
<!DOCTYPE html><html><head></head><body><script>alert(f1());
functionf2() {
return"Hello, I'm here";
};
functionf1() {
returnf2();
};
</script></body></html>
Solution 4:
You Can also Pass the context this
to the second function . However , in this case , you must call f2 as following:
function f1(){
return f2.call(this)
}
--
function f2(){
return123
}
UPDATE :
Passing context is very useful when you have Oriented Object Programming (OOP
):
I.E :
function Person(bornYear){
this.born=bornYear ;
this.age=Age.call(this,2014);
returnthis;
}
function Age(currentYear){
return currentYear-this.age;
}
If you note , this.age
is not undefined because the context this
has been passed from Person
function to Age
function.
Test this example :
var abdennour=newPerson(1989);
console.log(abdennour.age) // 25
Post a Comment for "Javascript : Access Return Of Other Function"