So I've been trying to figure out prototypal inheritance in Javascript and I'm still confused on one point. Let's say I want to make a constructor function for a person with a few functions of it's own.
function Person(name) {
this.name = name;
this.sayName = function() {
console.log("My name is " + name);
}
}
var john = new Person("John");
john.sayName();
So in this case I've created an object and called a function, however this doesn't seem to be the efficient way to do it. Another example I've seen this is this:
function Person(name) {
this.name = name;
}
Person.prototype.sayName = function() {
console.log("My name is " + name);
}
var john = new Person("John");
john.sayName();
Now I've read that the second object is more efficient because it's not storing the sayName function within itself, instead it's going up the prototype chain until it finds it within Persons prototype object.
What I'm unsure about is which I should use for complicated constructor functions. The first snippet, in my opinion, is much much easier to read than the second because there is a clear hierarchical structure to it, but the second snippet is supposedly more efficient.
In a real world scenario, which style of constructor function would I be more likely to use?
Edit: I have a follow up question. Is there any way to make the second snippet more readable?