An example of a class implementation using Javascript, showcasing the this keyword.
This file contains 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
//Create Class | |
class Dog { | |
//Assign properties to the newly created object in the constructor using "this" | |
constructor(name, breed, age) { | |
this.name = name; | |
this.breed = breed; | |
this.age = age; | |
} | |
bark() { | |
console.log("Bark bark!"); | |
} | |
/* Update properties using set methods; set updates the "this" properties | |
* of the object. | |
*/ | |
setName(name) { | |
this.name = name; | |
} | |
setBreed(breed) { | |
this.breed = breed; | |
} | |
setAge(age) { | |
this.age = age; | |
} | |
getName() { | |
return this.name; | |
} | |
getBreed() { | |
return this.breed; | |
} | |
getAge() { | |
return this.age; | |
} | |
} | |
//Create new Dog object | |
const myDog = new Dog("Isabelle", "Golden Retriever", 2); | |
console.log(myDog); //Dog { name: 'Isabelle', breed: 'Golden Retriever', age: 2 } | |
//Update name property using setName method | |
myDog.setName("Molly"); | |
console.log(myDog); //Dog { name: 'Molly', breed: 'Golden Retriever', age: 2 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment