Is this code,
function Person() {
function myMethod() {
alert ('hello');
}
this.method = myMethod;
}
equivalent to:
function Person() { }
Person.prototype.method2 = function() {
alert ('hello');
};
If yes, which method definition should I use and why?
They are functionally equivalent in your simple example, but behind the scenes work very differently. The
prototypeproperty on a function is really the “prototype template”. It says “whenever an object is made and I am used as the object’s constructor, give them this object as their prototype”.So all
Persons created in your second example share the same copy of themethod2method.In the first example, each time the interpreter encounters the
functionkeyword, then it creates a new function object. So in the first example, each instance ofPersonhas their own copy of themyMethodmethod. The vast majority of the time this doesn’t matter. But this first approach uses more memory, and sometimes that does matter.They are not functionally equivalent in more interesting cases. In the first example,
myMethodcan access local variables defined inPerson, but the second example cannot, as one difference.