简体   繁体   中英

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?

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"));

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM