0

I am reading John Resig's slideshow http://ejohn.org/apps/learn/#78 Its not clear to me why i need to include .prototype in the line Me.prototype = new Person();

function Person(){}
Person.prototype.getName = function(){
  return this.name;
};

function Me(){
  this.name = "John Resig";
}
Me.prototype = new Person();

var me = new Me();
assert( me.getName(), "A name was set." );
Geek Num 88
  • 5,264
  • 2
  • 22
  • 35

1 Answers1

0

Think of it this way, if every person is going to have a name, it's easier to assign the getName function to it's prototype.

In this case, you have a Person that has a prototype function to get a name, and a few lines below you have a Me function that assigns a name by default. Since we want to incorporate the getName function, we use the Person which already has that function object built-in. When you construct Me() and assign to me you can call getName() and use that to return the name, which by default is "John Resig"

The same thing can be achieved without prototype, like this

function Me(){
  this.name = "John Resig";
  this.getName = function () {
    return this.name;
  }
}

var me = new Me();

...BUT by using prototype, it helps create objects a lot faster, you can refer to this answer as well.

Community
  • 1
  • 1
C. S.
  • 805
  • 6
  • 6