3

I would like to clarify this doubt, but there may be solutions I don't know, so please help me. Generally while writing code we call a function

function call(a){
   /*some task*/
}

as

var a = "HELLO";
var data = call(a);

so the passing value will be processed inside the function call() and return some value to data.

But in the case of calling some builtin JavaScript functions like toString(), toLowerCase(), we won't pass the value inside the function rather we call the function like a.toLowercase().

How does this type of function call work behind the scenes, and is there any way to call the custom functions like the way the builtin functions are being called? Thanks in advance.

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
ram vinoth
  • 472
  • 4
  • 14

2 Answers2

3

I think possible reason could be these functions are bind to String Object prototype that's why you are able to call it as a.toLowerCase().
E.g: String.prototype.toLowerCase()

I guess if you try adding function to prototype of String Object. You will be able to call it in above fashion.
For e.g. :

String.prototype.distance = function (char) {
    var index = this.indexOf(char);

    if (index === -1) {
        alert(char + " does not appear in " + this);
    } else {
        alert(char + " is " + (this.length - index) + " characters from the end of the string!");
    }
};

"Hello".distance("H");

Above example is from Link: javascript: add method to string class

Tavish Aggarwal
  • 1,020
  • 3
  • 22
  • 51
2

you are actually referring to methods, which differ slightly from functions (they can be imagined as an OOP equivalent of functions, anyway). Basically every primitive in javascript (like String, Number, etc.) can be used as an object:

var foo = "Bar"; // Bar
var baz = foo.toLowerCase() // bar

foo here is a string. When using the toLowerCase method, javascript actually wraps the string in a String object, in order to make its methods available for use.

// behind the scenes
var magicTemporaryFoo = new String(foo);
var magicTemporaryFooMethodResult = magicTemporaryFoo.toLowerCase();

If you want to start using objects and their methods, i suggest you a very good read, "You don't know Js - This & Object Prototypes"

Loris Topa
  • 91
  • 2