Most of the function had to run by adding a parameter but in this case I just want to work like this:
JavaScript
x
10
10
1
let value = "test";
2
3
value.funcTest();
4
5
function funcTest(){
6
7
return "value replaced" + value;
8
9
}
10
instead of
JavaScript
1
10
10
1
let value = "test";
2
3
value = funcTest(value);
4
5
function funcTest(x){
6
7
return "value replaced" + x;
8
9
}
10
is there a way to pull this off?
Advertisement
Answer
Given
JavaScript
1
3
1
let value = "test";
2
value.funcTest();
3
It’s only possible if you add a method to String.prototype
– which is a very bad idea and shouldn’t be used.
JavaScript
1
5
1
String.prototype.funcTest = function() {
2
return "value replaced" + this;
3
}
4
let value = "test";
5
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.
JavaScript
1
7
1
const obj = {
2
value: "test",
3
funcTest() {
4
return "value replaced" + this.value;
5
}
6
}
7
console.log(obj.funcTest());