Javascript Function with String/Object attached to it

Javascript Function with String/Object attached to it

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

Javascript Function with String/Object attached to it

Leave a Reply

Your email address will not be published. Required fields are marked *