-2

I want to get variables before a dot like this:

"hello".myFunction();

I want to get "hello". I tried using this code and I thought that this is obviously not gonna work.

function myFunction(){
  return value;
}

But it doesn't work. I always getting this error.

TypeError: "hello world".myFunction is not a function. (In '"hello world".myFunction()', '"hello world".myFunction' is undefined)

Phil
  • 157,677
  • 23
  • 242
  • 245
Alken Rey
  • 3
  • 4
  • 1
    `hello` is a string which does not have `myFunction` method on it, why not simply pass `myFunction('hello')` and use it in `myFunction` – Code Maniac Jun 07 '19 at 04:51
  • `"hello"` is not a variable, it's a string literal, resulting in a string value. Please provide a better explanation of what you are trying to do. If generally you want to get a reference to the object you are calling a method on, you can do that via `this`: `({foo: 42, bar() { console.log(this); }).bar()` – Felix Kling Jun 07 '19 at 04:51
  • I want to use it like `toUpperCase()`. I'm just curious. – Alken Rey Jun 07 '19 at 04:58

3 Answers3

3

Using String.prototype and this keyword

String.prototype.myFunction = function() {
  document.body.innerText = this
}

"hello".myFunction();
User863
  • 19,346
  • 2
  • 17
  • 41
1

If you want to use it like toUpperCase(), try this.

String.prototype.myFunction = function() {
  return this.toUpperCase();
}

"abc".myFunction() // Evaluates to ABC
Agoose Banwatti
  • 410
  • 2
  • 13
0

As of now you are using a string and calling a user defined function on string. That can be accomplished by prototype overriding. So you can add one function on String object and use it. check this link....

Add method to string class

String.prototype.myFunction = function(a){

   return a;
}

"hello".myFunction("Done");
Hemant
  • 391
  • 1
  • 2
  • 10