Search code examples
javascriptclassinstancefunction-prototypes

Why does prototype need to be accessed via instance?


I'm trying to create a class constant, but I guess my novice-level understanding of JavaScript is showing. When this code executes:

var Class = function() {};
Class.prototype = { CONST : 1 };
var instance = new Class(),
c1 = instance.CONST,
c2 = Class.CONST;

the result is that c1 === 1 and c2 === undefined. Why isn't c2 === 1? Doesn't JavaScript look up the prototype chain for Class?


Solution

  • what you trying to do is what would be called a class static method in other language.
    To do that in Javascript you have to write

    Class.CONST = 1; then you can call it with Class.CONST;

    if you try to access it with instance method like new Class().CONST, it would be undefined

    Back to your question, everything in Class.prototype is only accessible to an instance of the object(ie, created via new), not Class itself. Why?

    Consider the implementation of new

    Function.method('new', function () {
        var that = Object.create(this.prototype);
        var other = this.apply(that, arguments);
        return (typeof other === 'object' && other) || that;
    });
    

    first Object.create(this.prototype) create a brand new object which inherited from this.prototype which u declared via Class.prototype = { Const : 1 }, then it call this.apply(that, arguments), which just call your declared Class function using that as the this variable. then it return the object. You can see that the Class function is simply used as a way to stuff things into the newly born object create via new. and only the object created has access to the prototype methods.