Search code examples
javascriptprototype-programming

What does "the prototype belongs to the class not the instance" mean in javascript?


I asked the question:

Why cant I declare a constructor instantiate an object and then access the prototype?

And you can see that I have marked the answer. I understand the response but Im a bit confused as to what he means by:

The prototype belongs to the class, not the instance:

Does this mean that javascript has a class in this example? I thought javascript was classless? It only has function constructors... At what point does a function constructor become a class? Is it when you add other members to it using the .prototype accessor?


Solution

  • Actually class is an OOP term, not really javascript. What is meant is that the prototype belongs to the constructor. So in

    function MyConstructor(prop){
       this.foo = prop || 'foo';
    }
    MyConstructor.prototype.bar = 'allways bar';
    var mc1 = new MyConstructor('I am mc1'), 
        mc2 = new MyConstructor('I am mc2');
    
    alert(mc1.bar) ; //=> allways bar
    alert(mc2.bar) ; //=> allways bar
    alert(mc1.foo) ; //=> I am mc1
    alert(mc2.foo) ; //=> I am mc2
    

    bar belongs to the constructors (MyConstructor) prototype. It will always be 'allways bar', for every instance. foo is an instance property (with a default value 'foo') and can be assigned with a different value for every instance.