0

I am quite newish at nodejs and javascript in general, and I have been trying to figure out how to make a function that executes on a variable, e.g.

var string = "Hello there";
var string1 = "Hello there again"
string = string.function();
string1 = string.function();

I am aware that this can be achieved by doing something like this function(string);, but I am a massive fan of more "inline code" and would like a nicer way to do it.

  • 1
    Not sure what you looking for, this? [javascript: add method to string class](https://stackoverflow.com/questions/8392035/javascript-add-method-to-string-class) – Alex K. Aug 11 '17 at 11:10
  • Just a warning. Modifying the prototype of a Javascript Object that you don't own, such as String, can potentially lead to complications. https://stackoverflow.com/questions/14034180/why-is-extending-native-objects-a-bad-practice – Khauri Aug 11 '17 at 11:17
  • Possible duplicate of [javascript: add method to string class](https://stackoverflow.com/questions/8392035/javascript-add-method-to-string-class) – Kayvan Mazaheri Aug 11 '17 at 11:20

3 Answers3

0

To achieve this you make your string variable an object

var string = {
   text: "Hello there",
   func: function(value) {
       return value;
   }
}
string.func(string.text); // Hello there

Edit: If you want your function to work on all strings add a method in String.prototype like so

String.prototype.your_function = function (char) {
  // work on char here
  return char
};
Prasanna
  • 4,125
  • 18
  • 41
0

I think this what you need

String.prototype.function = function ()
{
    return this + " world";
};
    
var x = "hello";
var y = x.function();
console.log(y);
Ali Faris
  • 17,754
  • 10
  • 45
  • 70
0

You can add custom functions to built in JavaScript object prototypes to your need.

For example in the case of your string approach, you can add a custom property to String.prototype like this:

String.prototype.myFunction = function() {
    return 'Value from myFunction: ' + this.valueOf();
}

And when you declare a string you can go and call your new function inline:

var s = 'my string';
s.myFunction();

And it will return:

"Value from myFunction: my string"

Hope it helps!

Szabolcs
  • 3,990
  • 18
  • 38