Created
May 6, 2019 14:23
-
-
Save wingleungchoi/72e8dac8ef464fea679d2d52b1584dcf to your computer and use it in GitHub Desktop.
Dog Class example in Javascript
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
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