Reputation: 852
I have this code, and a bit of a beginner's problem:
function findfruit (food){
var fruitvalues = ["apple", "orange", "banana", "mango", "kiwi", "watermelon"];
if (fruitsvalues.indexOf(food) != -1){
return true;
}
else {
return false;
}
}
var food = prompt("Write down any food you like");
findfruit(food) // returns always the correct answer, true or false
So here is the thing: This works well without problems, but if I do:
String.prototype.fruit = findfruit;
and then I try to make
if (food.fruit != true) {
alert("your food is not a fruit");
}
else {
alert("your food is a fruit");
it doesn't work, and it always results "false". I suspect that my problem is that when I invoke food.fruit
, the function findfruit
starts without using the string variable food
that I just created, but I don't understand why. I am just reading tutorials as for how to use prototype
, and I cannot find anything wrong (although I am sure there is something).
I would appreciate any help. I know this must be pretty easy, but the other questions about prototype that I found here couldn't help.
Thanks!
Upvotes: 0
Views: 55
Reputation: 7328
1) Writing food.fruit
is not a function invocation. It will just return the function itself (which obviously can't be equal to true).
2) You can access the object from which the function is invoked as this
. It won't be passed as an argument to your function (this isn't Python). The correct implementation is
String.prototype.fruit = function() {
var fruitvalues = ["apple", "orange", "banana"];
return (fruitvalues.indexOf(this.toString()) != -1);
}
3) Adding functions like this to prototypes of built-in types is discouraged. It's tempting, but you have to ask yourself: "Is this generic enough that I will need it everywhere in my program ?".
Upvotes: 1
Reputation: 288
If you simply use this to reference the string, you'll actually be scoped to the function. this.valueOf will look to the parent object (String).
String.prototype.fruit = function () {
var fruitvalues = ["apple", "orange", "banana", "mango", "kiwi", "watermelon"];
if (fruitvalues.indexOf(this.valueOf()) != -1){
return true;
}
else {
return false;
}
}
var food = 'apple';
if (food.fruit() != true) {
console.log("your food is not a fruit");
}
else {
console.log("your food is a fruit");
}
Upvotes: 0