obj1 and obj2 are slightly different, i'll give you a quick explanation about prottypal inheritance in JavaScript.
A prototype is an object, just like any other object.
Every object that has a prototype will inherit from it all the properties and methods, overwriting them in case they are already defined in the object. Prototype references are live, this means, whenever you modify an object that's a prototype of another object, the changes reflect in that object.
You are using the pseudo-classical inheritance method, by wich you define a Constructor
function that will return instances of a "class". All the instances of that class will have as their prototype object the object defined at: Constructor.prototype
, and you can add methods or propertys to that prototype, and those will be added to every instance of the "class".
Why are obj1 and obj2 different?
obj1 doesn't hold a direct reference to the fn
method, instead it holds a reference to the prototype, which has the method, and therefore obj1 has it aswell.
obj2 has a direct reference to the method, this means it's an own property of the object.
You can change the fn method of obj1 by changing the prototype's method, and any other instance of MyObject (like obj1) will be changed aswell.
But you can't do that in obj2, if you modify obj2's method you'll just replace the method of that instance.
I hope you got something, just ask if you have any doubts.
About the writing "class": JavaScript does't have classes, it emulates Class inheritance with prototypes, you can use crude prototypal inheritance using Object.create
, and you'll see it's way easier.