-1

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?

Rakushoe
  • 118
  • 11
  • No. `value.funcTest()` would mean that `funcTest()` would have to be a method on the string that is in the `value` variable. But, that's not a method of strings and you shouldn't make it a method of strings. If you can explain a bit more about "why" or "what you're really trying to accomplish", then we could perhaps offer some other architectural ideas. You could make a class that contains an instance variable that is a string and make `funcTest()` be a method on that class. – jfriend00 Mar 21 '22 at 04:18
  • the code is really complicated i am just simplifying it here.. but i got the answer below anyway thanks.. – Rakushoe Mar 24 '22 at 04:29
  • FYI, for the future. Make-up or pseudo-code rarely gets you the best answer here because so much of the real details of a question are in your specific code and only when you show us your real code can we help you with it in ways that you don't even know to ask about. So, you will generally get faster, more accurate and more useful answers if you post the relevant portions of your real code. – jfriend00 Mar 24 '22 at 05:55
  • maybe next time thanks for the info though.. – Rakushoe Mar 25 '22 at 00:14

2 Answers2

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());
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

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.

frielmv
  • 140
  • 10