I want to know the difference between the following two code snippets
What I understand is this is static because without creating an instance with new keyword, getCookie and setCookie functions can be called.
var CookieHandler = function () {};
CookieHandler.getCookie = function (key) {
};
CookieHandler.setCookie = function (key, value) {
};
And this is instance. In this case you need to create an instance to call the functions.
var CookieHandler = function () {};
CookieHandler.prototype.getCookie = function (key) {
};
CookieHandler.prototype.setCookie = function (key, value) {
};
I was a java programmer and barely understanding JS concepts please help me with this.
In Javascript, any function is also an object, so any function can have properties assigned to it. That's what your first block of code is doing. It is just assigning properties to the
CookieHandler
function. If CookieHandler is meant as an object definition, then though not exactly identical, these are analogous to class static properties in other OO languages.If it is not meant as an object definition, then CookieHandler is like a Javascript namespace and
getCookie
andsetCookie
are like properties in that namespace.Your second block of code is assigning properties to the prototype. These properties will be inherited by an instantiated CookieHandler object.
So, with your first block of code:
You can just freely call
CookieHandler.getCookie()
at any time.CookieHandler
is like a namespace object andgetCookie
andsetCookie
are properties on the namespace.If you create a CookieHandler object such as:
Then,
x
would not havegetCookie()
orsetCookie()
methods. Those methods only exist on theCookieHandler
object. They are not inherited by instances of CookieHandler.With your second block of code:
you are defining properties that instances of
CookieHandler
will inherit (instances inherit properties on the prototype). So, when you do:So, use the
prototype
when you want to define properties (usually methods) that instances of the object will inherit. If you aren't trying to define instance methods, then just put the methods on any object as in your first block of code.