A Pen by Afaq Ahmed Khan on CodePen.
Created
November 17, 2018 12:39
-
-
Save afaqahmedkhan/b2befe5b8084fb5c0ec3de46030720a4 to your computer and use it in GitHub Desktop.
Object Oriented Programming: Create a Method on an Object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let dog = { | |
name: "Spot", | |
numLegs: 4, | |
sayLegs: function() {return "This dog has " + dog.numLegs + " legs.";} | |
}; | |
dog.sayLegs(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
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."