I'm trying to return the string that called the function.
But it doesn't return the string… it returns an array.
String.prototype.testing = function testing() {
if (this === "what") {}
return this //Should return - this is a string
}
x = "this is a string"
y = x.testing()
console.log(y)
JavaScript has both String objects and string primitives. In a String.prototype method in loose mode, this is a string object. (In strict mode, it's whatever the method was called on, which is frequently a string primitive.) What you're seeing from console.log isn't an array, it's just how that particular console implementation outputs a String object rather than string primitive:
console.log(new String("hi"));
There is a bug in the code, though: this === "what" will never be true in loose mode, because "what" is a string primitive, but this is a String object, and === isn't allowed to coerce. You'd want this.toString() === "what" or this == "what". You'd probably also want to do something in the block attached to the if. And if you want to return a string primitive when returning this, you might want return this.toString(); at the end.
E.g., something like:
String.prototype.testing = function testing() {
if (this == "what") {
return "it was what";
}
return this.toString();
};
var x = "this is a string";
var y = x.testing();
console.log(y);
x = "what";
y = x.testing();
console.log(y);
Or using strict mode, something like this:
"use strict";
String.prototype.testing = function testing() {
if (this == "what") { // Could still be either a primitive or object, depending
return "it was what";
}
return this; // No need for toString here
};
var x = "this is a string";
var y = x.testing();
console.log(y);
x = "what";
y = x.testing();
console.log(y);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With