Meaning of prototype in javascript

Viewed 4903

I wrote short code of inheritance of reader from Person:

<script>

/* Class Person. */
function Person(name) {
    this.name = name;
}

Person.prototype.getName = function() {
    return this.name;
}

var reader = new Person('John Smith');
alert(reader.getName());

</script>

Alternatively I can delete the line of Person.prototype.getName = function() { return this.name; } and create it in the Person object. For example

<script>
/* Class Person. */
function Person(name) {
    this.name = name;
    this.getName = function() { return this.name;}
}

var reader = new Person('John Smith');
alert(reader.getName());

</script>

I got the same result when invoking getName() in both these cases. So how are they different?

6 Answers

When you add any function with this.functionname to any object constructor every object created by that constructor makes their own copy of that function which also takes memory. Imagine if you have several objects created by same constructor and how much memory it will take. on other hand when you creates it with cunstructorName.prototype.functionName function loads only once in memory and every object shares same prototype function constructor. this approach makes your code faster in loading and operation and also saves a big chunk of memory.

Related