-1

I'm trying to do a function like .split() or .replace() or .remove(), i think is like a prototype function, how i can make this example works:

this.logThis = function(a) {
  console.log("The " + this + "is cool like a " + a);
}

var food = "apple";
food.logThis("orange");

To get this Output:

> "The apple is cool like a orange"

Important: I need the most short code possibly, pure javascript, NO JQUERY

Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
IchQuile
  • 27
  • 4

2 Answers2

6

If you want to be able to call the function on a string, you'll need to extend the String prototype:

String.prototype.logThis = function(a) {
  console.log("The " + this + " is cool like a " + a);
}

var food = "apple";
food.logThis("orange");

This'll work, but you might want to alter it slightly to use a more modern JavaScript syntax:

String.prototype.logThis = function(a) {
  console.log(`The ${this} is cool like a ${a}`);
}

const food = "apple";
food.logThis("orange")

It is also worth pointing out that extending native objects is considered by many to be a bad practice (here's why), so you might rather alter your function to avoid this.

Here's one way of doing that:

const obj = {
  food: 'apple',
  logThis(a) {
    console.log(`The ${this.food} is cool like a ${a}`);
  }
}

obj.logThis("orange");
James Hibbard
  • 16,490
  • 14
  • 62
  • 74
2

I will preface this by saying that generally, you don't want to extend prototypes. For that I will refer you here.

However - if you really wanted to, you could:

String.prototype.logThis = function(a) {
  console.log("The " + this + " is cool like a " + a);
}

var food = "apple";
food.logThis("orange");
Tim VN
  • 1,183
  • 1
  • 7
  • 19
  • Can i use a custom replacing of "String." with "Int" or "Object", for apply the function to any type of variable? – IchQuile Apr 29 '19 at 10:32
  • You might want to take a look at Classes: https://javascript.info/class – Tim VN Apr 29 '19 at 11:05
  • Thankyou, i already Works good, i replace with Number.prototype.LogThis(); using a example with intergers and works so nice... i can mix absolutly all with that... – IchQuile Apr 29 '19 at 11:08