-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

  • You want to make `aFunction` a string method? – deceze Jun 14 '18 at 12:45
  • Like? https://stackoverflow.com/questions/8392035/javascript-add-method-to-string-class – Eddie Jun 14 '18 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? – Pointy Jun 14 '18 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`. – feeela Jun 14 '18 at 12:46
  • I want it to be similar to charAt() native javascript function, which is used as: string.chartAt(0) – Andreas Karps Jun 14 '18 at 12:46
  • It would be more clear to have a "use case" and the need to do this, probably there might be other options than just changing the string to have a certain method by prototype or methor property for that value – juan garcia Jun 14 '18 at 12:49
  • Read about `prototype` in javascript – Akhilendra Jun 14 '18 at 12:50
  • @AndreasKarps Keep in mind that extending built-in objects' prototype is bad practice. Same as defining global variable. It might cause name conflicts with another code or future standards. At least use `Object.defineProperty` to make this property non enumerable. – Yury Tarabanko Jun 14 '18 at 13:23

1 Answers1

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);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62