Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return values with call() or apply() in JavaScript

Tags:

javascript

Is there a way to get the function's return value when it's called from call() or apply()?

My scenario:

I have a function that works fine with apply() function. On object contructor:

var someObject = new SomeObject({NameFunction: "MakeNames"});

On a loop in the object's method:

var name = "";
for (var i = 0; i < data.length; i++) {
    name = window[this.NameFunction].apply(null, [data[i]]);
}

And the MakeNames function:

function MakeNames(data)
{
    return data.FirstName + " " + data.LastName;
}

That var name stay empty cause apply doesn't return any value from the function. Note that I'm sure the function is called and the argument is passed succesfully. Please don't tell me to use name = MakeNames(data[i]); directly, because it is obvious that I don't want this solution.

It doesn't matter if it is apply, call or whatever JavaScript has to make this work, if works.

How can I achieve this?

like image 946
DontVoteMeDown Avatar asked May 22 '13 12:05

DontVoteMeDown


1 Answers

The result of:

window[this.NameFunction.toString()].apply(null, [data[i]])

is exactly the same as:

MakeNames(data[i])

since the only difference is the value of this in the MakeNames function, and since this isn't used, it can't make any difference. The use of apply doesn't change whether the function returns a value or not, or what the value is.

Whatever issue you have, it isn't in the (bits of) posted code.

like image 157
RobG Avatar answered Oct 21 '22 07:10

RobG