Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save afaqahmedkhan/b2befe5b8084fb5c0ec3de46030720a4 to your computer and use it in GitHub Desktop.
Save afaqahmedkhan/b2befe5b8084fb5c0ec3de46030720a4 to your computer and use it in GitHub Desktop.
Object Oriented Programming: Create a Method on an Object
let dog = {
name: "Spot",
numLegs: 4,
sayLegs: function() {return "This dog has " + dog.numLegs + " legs.";}
};
dog.sayLegs();
@afaqahmedkhan
Copy link
Author

Objects can have a special type of property, called a method.

Methods are properties that are functions. This adds different behavior to an object. Here is the duck example with a method:

let duck = {
  name: "Aflac",
  numLegs: 2,
  sayName: function() {return "The name of this duck is " + duck.name + ".";}
};
duck.sayName();
// Returns "The name of this duck is Aflac."

The example adds the sayName method, which is a function that returns a sentence giving the name of the duck.

Notice that the method accessed the name property in the return statement using duck.name. The next challenge will cover another way to do this.

Using the dog object, give it a method called sayLegs. The method should return the sentence "This dog has 4 legs."

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment