Skip to content

Instantly share code, notes, and snippets.

@wingleungchoi
Created May 6, 2019 14:23
Show Gist options
  • Save wingleungchoi/72e8dac8ef464fea679d2d52b1584dcf to your computer and use it in GitHub Desktop.
Save wingleungchoi/72e8dac8ef464fea679d2d52b1584dcf to your computer and use it in GitHub Desktop.
Dog Class example in Javascript
class Dog {
constructor(nameOrDog = '') {
if (nameOrDog instanceof Dog) {
this.name = nameOrDog.getName();
} else if ((typeof nameOrDog) === 'string') {
this.name = nameOrDog;
} else {
// throw new Error('type is not supported');
}
}
setName(name) {
this.name = name;
}
getName() {
return this.name;
}
}
myDog = new Dog( "nathan");
myDog.setName( "nathan II" );
/* Call another class method to get Dog's Name */
myDogName = myDog.getName();
/* You can access instance variable as follows as well */
console.log("myDogName: " + myDogName );
clonedDog = new Dog(myDog);
/* You can access instance variable as follows as well */
console.log("cloned dog name: " + clonedDog.getName() );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment