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?
var empty = {}; // Outputs: Function Object() console. log(empty. constructor); Every time you create a new object via an object literal (the {} ), behind the scenes JavaScript invokes the Object constructor to create the object, just as if you'd used new Object() .
JavaScript has two types of objects: function object and non-function object. Conceptually, all objects have a prototype (NOT A PROTOTYPE PROPERTY).
There is a clear reason why you should use prototypes when creating classes in JavaScript. They use less memory. When a method is defined using this. methodName a new copy is created every time a new object is instantiated.
To answer your question simply, there is no real difference. Straight from the MDN web docs definition: JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript's existing prototype-based inheritance.
They are functionally equivalent in your simple example, but behind the scenes work very differently. The prototype
property 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 Person
s created in your second example share the same copy of the method2
method.
In the first example, each time the interpreter encounters the function
keyword, then it creates a new function object. So in the first example, each instance of Person
has their own copy of the myMethod
method. 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, myMethod
can access local variables defined in Person
, but the second example cannot, as one difference.
In the first scenario, when you create a new person, var person1 = new Person();
, it will have its own copy of myMethod
. If you create 100 Person objects, they will each have their own copy of this method.
Using a prototype, every new Person object will share the method definition. This is much more memory efficient since there will only be one copy of the method.
If you are planning on having several Person objects, the second way is better.. but if there are only a few Person objects, it won't matter that much.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With