-1

In javascript, I want to write a function which is called as follows:

var x = 'testString'
var y = 'anotherstring'
var z = 0

var result = x.aFunction(y, z)

function aFunction(y, z) {
  ...
}

This is the first time I am attempting this, my question is how can I get and use the value of x in the function aFunction, without actually referring to the declared variable.

I tried looking for this but I cannot find anything. If there is a post specifically for this that anyone knows about, please let me know.

Thanks

8
  • You want to make aFunction a string method? Commented Jun 14, 2018 at 12:45
  • Like? stackoverflow.com/questions/8392035/… Commented Jun 14, 2018 at 12:45
  • 2
    Why do you want to do ... well, whatever it is you're asking? What is the actual problem you're trying to solve? Commented Jun 14, 2018 at 12:46
  • If the function aFunction is defined in the prototype you can refer to the outer variable on which the function was called using this. Commented Jun 14, 2018 at 12:46
  • I want it to be similar to charAt() native javascript function, which is used as: string.chartAt(0) Commented Jun 14, 2018 at 12:46

1 Answer 1

1

You need to use String.prototype.aFunction so that you can add a custom function aFunction() to the prototype of String such that it can be invoked by a string variable. Also this.toString() inside the prototype function will give you the value of the x variable (calling string)

var x = 'testString'
var y = 'anotherstring'
var z = 0

String.prototype.aFunction = function(y, z){
  console.log(this.toString());
  return y+z;
}
var result = x.aFunction(y, z);
console.log(result);

Sign up to request clarification or add additional context in comments.

4 Comments

"how can I get and use the value of x in the function aFunction?"
great, thanks, found a similar post that also helped
@AndreasKarps cool. I have updated the answer check it out
@deceze thanks for pointing that

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.