Skip to content

Instantly share code, notes, and snippets.

@KinoAR
Last active November 27, 2018 16:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KinoAR/4e0ce8a25f62547324d1926a27ea6cac to your computer and use it in GitHub Desktop.
Save KinoAR/4e0ce8a25f62547324d1926a27ea6cac to your computer and use it in GitHub Desktop.
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