Could someone explain me why if I affect an object to a prototype, properties are not added to already existing instances of this object, while if I affect individually each property of the prototype, properties are added to all already defined instances. Example1 and example2 below illustrate my question (https://jsfiddle.net/tgyakpe0/5/). Result of the example is:
example 1 My father is English I am English
example 2 My father is English I am undefined
example 3 My father is English and lawyer I am English and lawyer
example 4 turnaround My father is English and lawyer I am English and lawyer
In example 4 I made a simple turnaround for this behaviour, but I wonder if it's a safe practice. Thank you.
/* example 1 */
function person1(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
var me1=new person1("lolo","lala",35,"blue");
person1.prototype.nationality="English";
var myFather1 = new person1("John", "Doe", 50, "blue");
document.getElementById("example1").innerHTML ="* example 1 <br>My father is " + myFather1.nationality+" <br>I am "+me1.nationality;
/* example 2 */
function person2(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
var me2=new person2("lolo","lala",35,"blue");
person2.prototype={nationality:"English"};
var myFather2 = new person2("John", "Doe", 50, "blue");
document.getElementById("example2").innerHTML ="* example 2 <br>My father is " + myFather2.nationality+" <br>I am "+me2.nationality;
/* example 3 */
function person3(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
var me3=new person3("lolo","lala",35,"blue");
person3.prototype.job="lawyer";
person3.prototype.nationality="English";
var myFather3 = new person3("John", "Doe", 50, "blue");
document.getElementById("example3").innerHTML ="* example 3 <br>My father is " +myFather3.nationality+" and "+myFather3.job+" <br>I am "+me3.nationality+" and "+me3.job;
/* example 4 */
function proto(f,prot){
for (k in prot) {
f.prototype[k]=prot[k];
}
}
function person4(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
var me4=new person4("lolo","lala",35,"blue");
prototo={job:"lawyer",nationality:"English"};
proto(person4,prototo);
var myFather4 = new person4("John", "Doe", 50, "blue");
document.getElementById("example4").innerHTML ="* example 4 <br>My father is " +myFather4.nationality+" and "+myFather4.job+" <br>I am "+me4.nationality+" and "+me4.job;