DontVoteMeDown
DontVoteMeDown

Reputation: 21465

Return values with call() or apply() in 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?

Upvotes: 5

Views: 8166

Answers (2)

RobG
RobG

Reputation: 147413

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.

Upvotes: 13

SeanCannon
SeanCannon

Reputation: 77976

I don't see in your code where data is set, or where data[i] would be an object that has the properties FirstName and LastName. Try a fail-over:

function MakeNames(data) {
    return (data.hasOwnProperty('FirstName')) ? data.FirstName + " " + data.LastName : 'John Doe';
}

Upvotes: 0

Related Questions