It is not entirely equivalent.
In both cases, you define a function (constructor) Person()
in the global namespace.
In the first case, you define a new function myMethod()
in a closure inside the Person()
function. Normally, the myMethod()
function would not be available after the function/constructor Person()
finishes. However, in this case you assign it to this.method
. Thus, when you run the constructor
var myPerson = new Person();
A new object is created, then the Person()
function is called with this
set to the new object. Therefore, your new object receives a method
field with myMethod
function bound to it.
In the second case, method2
is defined inside the Person.prototype
. In this case, when you call
var myPerson = new Person();
there will be no field defined directly inside your new object (as you do nothing with this
in the function Person
). However, every object contains a reference to its prototype. If the object is created by calling Person()
, this reference is set to Person.prototype
. Thus, your object will ultimately contain method2
, though not directly in itself, but in the prototype. So when you call
myPerson.method2();
the interpreter looks for method2
inside the myPerson
object and finds nothing, then it looks into the prototype of myPerson
, which is Person.prototype
and finds method2
, so it calls it.
Long story short: in the first your constructor creates the method, so every time you call the constructor, a new method is created and inserted to the new object. In the second case, the method is stored in the prototype, so every object you create will have the reference to the same instance of your method.