2
var Person = function(name, age) {
  this.name = name;
  this.age = age;
};



//Now create three instances of Person with data you make up

var p1 = new Person('Aaron', 32);
var p2 = new Person('Casey', 30);
var p3 = new Person('Greg',31);



//Now add a sayName method on your Person class that will alert the name of whatever Person instance called it.

I'm not sure how to add a method to an existing class. I'm new to JavaScript. I understand how to add new properties but not new functions.

Aaron
  • 49
  • 1
  • 1
  • 4

4 Answers4

5

Add the method to the Person prototype chain.

Person.prototype.sysName = function() {
    return console.log(this.name);
};
Sushanth --
  • 55,259
  • 9
  • 66
  • 105
2

var Person = function(name, age) {
  this.name = name;
  this.age = age;
};

Person.prototype.sayName = function () {
 alert(this.name)
}

var p1 = new Person('Aaron', 32);

p1.sayName() 

You can define Methods in using prototype

Person.prototype.myMethod = function() { ... }

TedMeftah
  • 1,845
  • 1
  • 21
  • 29
0

One way to do this is by using prototyping you can add a method to an object though doing: myObject.prototype.myMethod = function(){ ... }

Person.prototype.sayName = function(){
    console.log(this.name);
}

Another way can be directly adding it on the creation of Person, just note the method is duplicated for each instance in this case:

var Person = function(name, age) {
  this.name = name;
  this.age = age;

  this.sayName = function() {
      console.log(this.name);
  }
};
Spencer Wieczorek
  • 21,229
  • 7
  • 44
  • 54
  • Using the second option, will create a new function for every instance. Which is not recommended. – TedMeftah Sep 09 '16 at 21:17
  • 1
    @Mohamed-Ted I'm aware of that, was about to add it in as an edit. Although there is not a significant difference in most cases unless there are many thousands of instances being created. – Spencer Wieczorek Sep 09 '16 at 21:19
0

Person.prototype.sayName = function() { console.log(this.name) }

you can add a prototype function to the Person class and then each person has access to the function.

finalfreq
  • 6,830
  • 2
  • 27
  • 28