I am trying to understand prototype in JavaScript.
Both Example 1 and Example 2 mentioned below give same output.
EXAMPLE 1 [displays 'f1 l1']
function parent(fname, lname) {
this.firstName = fname;
this.lastName = lname;
this.fun1 = function () {
return this.firstName + " " + this.lastName;
};
};
function child() {};
child.prototype = new parent('f1', 'l1');
var objChild = new child();
alert(objChild.fun1()); // alert displays 'f1 l1'
EXAMPLE 2 [also displays 'f1 l1']
function parent(fname, lname) {
this.firstName = fname;
this.lastName = lname;
};
parent.prototype.fun1 = function () {
return this.firstName + " " + this.lastName;
};
function child() {};
child.prototype = new parent('f1', 'l1');
var objChild = new child();
alert(objChild.fun1()); // alert displays 'f1 l1'
The only difference between EXAMPLE 1 and EXAMPLE 2 is the way fun1() function is defined. My question is, when either way of defining the fun1() gives same output , what is the difference between the two.( I understand that my understanding of prototype is not clear ).
Please clarify