Functions with public property

Asked

Viewed 45 times

3

How is it possible to use a function as an object? More precisely, I would like to repeat the behavior of $http angular, where it is possible to execute a request in the following forms:

$http.get('url');

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

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

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

1 answer

1


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

The $http of the angular is basically this, a function with a number of other functions added to it as shortcuts to the main, in a very simplified way 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});
}
  • I did tests by setting the properties within the function (using this, var, return) and there was no way, when the solution was easier than I imagined... This way it is also possible to use the prototype right?

  • I can’t tell you exactly how it would be with prototype, but the way it works I believe it’s different, in his case I believe it would really be for objects created by new

Browser other questions tagged

You are not signed in. Login or sign up in order to post.