-1

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

refactor
  • 13,954
  • 24
  • 68
  • 103
  • @didierc a prototype does not work like a template. The prototype object always remains separate from the instances. – Pointy Jun 29 '14 at 17:50
  • @Pointy indeed, wrong analogy. That was probably the point on which OP was confused, so my comment actually did not help. Thank you for clarifying it! – didierc Jun 29 '14 at 18:06
  • The following answer explains in great detail what prototype is, how it's used and how you can use it for inheritance: http://stackoverflow.com/questions/16063394/prototypical-inheritance-writing-up/16063711#16063711 – HMR Jun 30 '14 at 01:26

2 Answers2

1

Your first example puts "fun1" on every parent instance. The second puts it on the parent prototype.

When you call objChild.fun1() in the first example, the JavaScript runtime will find the function on the "child" prototype object. In the second example, it won't find it there, but it will find it when it proceeds to check the "parent" prototype object.

That's not the best-practice way to establish an inheritance chain, by the way; there are some (admittedly confusing) details that that approach doesn't address. The relatively new Object.create() function is a better choice, and you can find information about it (and a "polyfill" for older browsers) on the MDN site. (If it's not clear, I mean setting child.protoype to a newly-instantiated "parent" object.)

Pointy
  • 405,095
  • 59
  • 585
  • 614
1

Second way is preferred if you want to have the same method fun1 for all objects. The first way, in opposite, allows you to have different implementations of this method for different objects.

Artem Volkhin
  • 1,362
  • 8
  • 22