Javascript static vs instance, prototype keyword

前端 未结 2 1245
春和景丽
春和景丽 2020-12-17 17:40

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, getC

2条回答
  •  一整个雨季
    2020-12-17 18:18

    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 and setCookie 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:

    var CookieHandler = function () {};
    CookieHandler.getCookie = function (key) {
    };
    CookieHandler.setCookie = function (key, value) {
    };
    

    You can just freely call CookieHandler.getCookie() at any time. CookieHandler is like a namespace object and getCookie and setCookie are properties on the namespace.

    If you create a CookieHandler object such as:

    var x = new CookieHandler();
    x.getCookie();    // does not work
    x.setCookie();    // does not work
    

    Then, x would not have getCookie() or setCookie() methods. Those methods only exist on the CookieHandler object. They are not inherited by instances of CookieHandler.


    With your second block of code:

    var CookieHandler = function () {};
    CookieHandler.prototype.getCookie = function (key) {
    };
    CookieHandler.prototype.setCookie = function (key, value) {
    };
    

    you are defining properties that instances of CookieHandler will inherit (instances inherit properties on the prototype). So, when you do:

    var x = new CookieHandler();
    x.getCookie();    // works
    x.setCookie();    // works
    

    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.

提交回复
热议问题