David G
David G

Reputation: 96855

Why does this function return as undefined?

String.prototype.parse = function(f) {
    alert(this.replace(f, ""));
};
var a = "Hello World";
parse.apply(a, ["Hello"]);

Is the code correct?

Upvotes: 1

Views: 424

Answers (2)

poke
poke

Reputation: 388393

No, that’s not correct. The function is defined as String.prototype.parse, so it is not available as parse (in fact, parse is undefined).

You could run it like the following:

String.prototype.parse.apply(a, ["Hello"]);

But actually, the reason why you add the function to the prototype of String is that you extend String objects with that function. So you actually should just run the function like this:

a.parse("Hello");

edit:

Oh, and in response to your question title “Why does this function return as undefined?”: The function doesn’t return anything, because you don’t tell the function to return anything. You could for example define it like this to return the replaced string (instead of alerting it):

String.prototype.parse = function(f) {
    return this.replace(f, "");
};

And then you could alert the return value of the function:

alert(a.parse("Hello"));

Upvotes: 6

bobbymcr
bobbymcr

Reputation: 24177

There is no such variable parse defined in your code sample. If you really want to apply the function later on, you should do this:

// Capture function as a local variable first
var parse = function(f) { alert(this.replace(f, "")); };
String.prototype.parse = parse;

Upvotes: 0

Related Questions