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?
When you put something on the prototype, every instance of the object shares the same code for the method. They are all using the same function instance.
When you simply put a method on
this, every object instance has its own copy of the same method.Using
prototypeis much more efficient. Note this is why typically methods are placed on the prototype, since you typically want all instances to use the same method, but properties are placed on the instance itself, because typically you don’t want all instances to share the same properties.For your comment, if you put a method on the constructor function of an object, then you have in effect created a “static” method. No instance of the object will have that method, they all must access it on the constructor function. So in your case,
Person.someMethod().