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: