سؤال

A few day ago I was looking at Superagent module and I was wondering how a code should be made to support a syntax like request('url', callback); and like request.get('url').end(callback); at the same time.

I tried to look at the source, but I didn't understand how it's made.

Can anyone tell me how can I do it?

هل كانت مفيدة؟

المحلول

If you're trying to define a module with a similar API...

Functions in JavaScript are a type of Object, so references to them can be passed around and they can be given properties, including other functions as methods.

In this case, request is just a function with get assigned as one of its properties:

function request(method, url) {
  // ...

  return new Request(method, url);
}

request.get = function(url, data, fn){
  var req = request('GET', url);

  // ...

  return req;
};

With either, the value returned is a Request instance, which has an end method that continues to return the instance.

Request.prototype.end = function(fn) {
  // ...

  return this;
};

This allows for a fluent API with method chaining:

request
  .get('...', function () {})
  .end(function () {});
  .end(function () {});
// that does the same as...
var req = request.get('...', function () {});
req.end(function () {});
req.end(function () {});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top