Skip to content

Instantly share code, notes, and snippets.

@KinoAR
Last active Nov 27, 2018
Embed
What would you like to do?
An example of a class implementation using Javascript, showcasing the this keyword.
//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