javascript – Functions with public properties

Question:

How is it possible to use a function as an object? To be more precise, I would like to repeat the behavior of the angular $http , where it is possible to execute a request in the following ways:

$http.get('url');

$http.post('url', data);

$http({
    method: 'get',
    url: 'url',
    ...
});

Note that the $http function can be either invoked directly or used as an object to get the get and post properties.

Answer:

A javascript function is also an object, and as such it can have values ​​and methods assigned to it like any other object.

Angular's $http is basically that, a function with a series of other functions added to it as shortcuts to the main one, in a very simple way it would be the following:

function $http(options) {
    //código
}

$http.get = function(url) {
    return $http({method : 'get', url: url});
}

$http.post = function(url, data) {
    return $http({method : 'post', url: url, data: data});
}
Scroll to Top