1

I am trying to understand how the cookie middleware works by looking at the source code. This middleware is going to replace the deprecated cookieParser(). https://github.com/jed/cookies/blob/master/lib/cookies.js

Need some help in explaining the very first sentence:

...

function Cookies(request, response, keys) {
  if (!(this instanceof Cookies)) return new Cookies(request, response, keys)

 ...
} ...
  1. What does "!(this instanceof Cookies)" do? Is it checking the "this" is the function itself?
  2. What is the purpose of this code?

Thanks a lot!

Trevor Dixon
  • 23,216
  • 12
  • 72
  • 109
Nicolas S.Xu
  • 13,794
  • 31
  • 84
  • 129
  • trevor's answer is correct, for basic introduction in constructor functions, prototype and the value of `this`: http://stackoverflow.com/a/16063711/1641941 – HMR Dec 10 '13 at 08:06

2 Answers2

3

It makes the new keyword optional and these equivalent:

var cookies = new Cookies();

var cookies = Cookies();

In javascript, an object will be instanceof of a function F if the object was constructed by doing new F() (or new G() where G is in the prototype chain of F).

When you call new F(), the function F is invoked, and within the function body, this refers to a new object that is an instance of F. If, however, you simply invoke F like F(), this is set to the global object (window in the browser and global in node.js).

The line in question is testing to see if the function Cookies was invoked with the new keyword (like new Cookies(...), in which case this will be an object that is an instance of Cookies and this instanceof Cookies will evaluate to true), or whether it was called without (like Cookies(...), in which case this will be some object that isn't an instance of Cookies). In the second case, the function is called with new and returned.

This lets the consumer of the API call Cookies with or without the new keyword and still get an object that is an instance of Cookies back. Without this check, calling Cookies without new would lead to unexpected results.

Also see:

Community
  • 1
  • 1
Trevor Dixon
  • 23,216
  • 12
  • 72
  • 109
1

This allows you to create an instance of Cookies with or without the new keyword. this refers to the instance. If you call the function without the new keyword, this will be the global object instead of a new instance.

sbking
  • 7,630
  • 24
  • 33