Skip to content Skip to sidebar Skip to footer

How Do I Add A Method To An Existing Object?

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 p

Solution 1:

Add the method to the Person prototype chain.

Person.prototype.sysName = function() {
    returnconsole.log(this.name);
};

Solution 2:

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.

Solution 3:

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

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

var p1 = newPerson('Aaron', 32);

p1.sayName() 

You can define Methods in using prototype

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

Solution 4:

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:

varPerson = function(name, age) {
  this.name = name;
  this.age = age;

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

Post a Comment for "How Do I Add A Method To An Existing Object?"