-4

Instead of using

function functionName(arg){
arg = 1;
}
name(arg);

I want to use something like the .toUppercase() function

function functionName(){
this = 1;
}
arg.name();

Is this possible?

KaZMa
  • 35
  • 6
  • 3
    Your question make zero sense to me. Can you try to rephrase it? – idmean Mar 15 '19 at 16:42
  • 3
    https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes – j08691 Mar 15 '19 at 16:43
  • I really can't get what you mean but you may mean somthing like arg.toString().toUpperCase() – Michel Hanna Mar 15 '19 at 16:44
  • Possible duplicate of [How do I write an extension method in JavaScript?](https://stackoverflow.com/questions/9354298/how-do-i-write-an-extension-method-in-javascript) – adiga Mar 15 '19 at 17:32

2 Answers2

1

You can extend the prototype of the string object in JavaScript

String.prototype.functionName = function () {
    return this; //do whatever you want to do it with the string
};

Now you are able to call this way mystring.functionName()

OsDev
  • 1,243
  • 9
  • 20
  • 1
    While it's true that it's possible to do that, you shouldn't _ever_ have to do that. –  Mar 15 '19 at 16:50
  • 1
    This is exactly what I wanted, thank you. @davmich its not about it being optimized, recommended or conventional. Its just to prove a point and I just wanted to know if it is possible. – KaZMa Mar 15 '19 at 16:55
1

add function inside the object

var arg = {
  name:function(str){
    return str;
  }
}

console.log(arg.name('sss'))
prasanth
  • 22,145
  • 4
  • 29
  • 53