'Executing a function that runs directly by adding it at the end of the variable

Most of the function had to run by adding a parameter but in this case I just want to work like this:

let value = "test";

value.funcTest();

function funcTest(){

return "value replaced" + value;

}

instead of

let value = "test";

value  = funcTest(value);

function funcTest(x){

return "value replaced" + x;

}

is there a way to pull this off?



Solution 1:[1]

Given

let value = "test";
value.funcTest();

It's only possible if you add a method to String.prototype - which is a very bad idea and shouldn't be used.

String.prototype.funcTest = function() {
  return "value replaced" + this;
}
let value = "test";
console.log(value.funcTest());

If you want to tie the string and a function together without using a function call of a separate identifier, a better approach would be to use an object instead, and put both in the object.

const obj = {
  value: "test",
  funcTest() {
    return "value replaced" + this.value;
  }
}
console.log(obj.funcTest());

Solution 2:[2]

I'm not entirely sure what you're trying to do, but maybe using an object would work:

let variable =
{
  value: 'test',
  funcTest: function()
  {
    return 'value is ' + this.value;
  }
};

If you don't want to have to add the parentheses you could also use a getter:

let variable=
{
  value: 'test',
  get funcTest()
  {
    return 'value is ' + this.value;
  }
};

This way you could just call variable.funcTest and it would do the same thing.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CertainPerformance
Solution 2 funny username