Whenever you create an object, such as a function, it inherits from the Object constructor, so this
var Class = function() {};
is an object, and it has it's own prototype
property that can be accessed with
Class.prototype
and you can create new properties on the prototype
object with
Class.prototype.testObj = {a:2, b:3};
if you wanted to access that, you would actually have to do
console.log(Class.prototype.testObj)
as that's where it is, a property added to the prototype
property of Class
.
When you use the new
keyword some magic happens, a whole new object is created (called an instance), and that object inherits from Class.prototype
, from the docs
When the code new Class(...) is executed, the following things happen:
A new object is created, inheriting from Class.prototype.
The constructor function Class is called with the specified arguments
and this
bound to the newly created object. new Class is equivalent to
new Class(), i.e. if no argument list is specified, Class is called
without arguments.
The object returned by the constructor function becomes the result
of the whole new expression. If the constructor function doesn't
explicitly return an object, the object created in step 1 is used
instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation
process.)