I don’t understand what is the essential difference between the following two ways of writing?
function Person() {
}
Person.prototype.age = function(n) {
return n;
}
var person = new Person();
person.age(9);
The above writing method uses the prototype to allow the instantiated object to call the function of the parent class.
The following method does not pass the prototype, but it is exactly the same in usage.
function Person() {
this.age = function(n) {
return n;
}
}
var person = new Person();
person.age(9);
In what aspects are the two comparable? Please advise, thank you!
There is a difference in memory saving
The first way, prototye definition, all descendants share a method definition, which only occupies one space in the memory. No matter how many instances you create, the age method of all instances points to this memory address.
The second method is defined in the constructor. Every time an instance is created, the definition of the age method will allocate a space that is exclusive to the instance. As more instances are created, the memory increases proportionally.
In summary, if it is a common method, please put it in the prototype.
The second way of writing is the constructor pattern, which is easy to use, but the main problem with this method is that each method must be recreated on each instance.
The first prototype pattern approach solves this problem by letting all object instances share the properties and methods it contains.
Simply put, the functions are the same, except that in most cases the methods are written in the prototype and the properties are written in the constructor, so the first method is more commonly used