Skip to content
Advertisement

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?

Advertisement

Answer

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());
Advertisement