DEV Community

Randy Rivera
Randy Rivera

Posted on • Edited on

Creating a Method on an Object

  • Continued.
  • 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 dog example with a method:

let dog = {
  name: "Anakin",
  numLegs: 4,
  sayName: function() {return "The name of this dog is " + dog.name + ".";}
};

console.log(dog.sayName()); // would print the string The name of this dog is Anakin.
Enter fullscreen mode Exit fullscreen mode
  • The example adds the sayName method, which is a function that returns a sentence giving the name of the dog. Notice that the method accessed the name property in the return statement using dog.name. The next challenge will cover another way to do this.

Top comments (0)