Javascript: Adding Methods to Objects

Contents

We can add functions to objects, as properties, and when that is done they are referred to as methods.

// We will create an object called someObject and a property of that object 
// will be a function called "add". The "add" function is now a METHOD.

var someObject = {
name: "Nick Coughlin",
height: "5'11\"",
hair: "brown",
age: 30,
isCool: true,
pets: ["max", "jewel", "bailey", "lola"],
add: function(x,y){
  return x + y;
  }
}

//to call the function we now must call it as a property of the object someObject

someObject.add(10,140)
//150

So why would we want to add methods to objects? Why not just keep our functions separate?

// adding methods to objects becomes useful for organizing functions that are similar,
// so that we can avoid namespace collisions.

var dog = {
  name: "lola",
  age: 5,
  sound: function(){
    return("woof woof");
  }
}

var cat = {
  name: "Mr. Puff",
  age: 8,
  sound: function(){
    return("meow meow");
  }
}

And if we run that in the console we get:

meow meow, woof woof in console

and an alternate way to add functions to objects is like this:

// we create an empty object named comments
var comments = {
}

// and then we add methods to the object

comments.add = function(x,y){
return x + y;
}

comments.subtract = function(x,y){
return x - y;
}

and we can see that that works in the console and returns the expected values:

adding and subtracting from comments

// The "this" keyword is used inside of a method to refer to the object that it is contained inside of
// It is a way of sharing data inside of an object

// Lets take a simple array of comments inside of an object

var article = {};
article.comments = ["great article", "I hate your face", "I find this content offensive"];

// and now let us write a function that prints the comments

article.printComments = function(){
  this.comments.forEach(function(el){     //el is short for element
    console.log(el);
  });
}

// so we just added a function to the object "article" called printComments that
// references the object that it's inside of (articles) and then the array inside
// that it wants to loop over (comments)

and that gives us the following result:

a list of comments