Last active
February 26, 2020 17:54
-
-
Save munkacsitomi/7f8b255b28cda247973dfa947e1fb7c9 to your computer and use it in GitHub Desktop.
Getter/Setter methods in JS
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 NinjaCollection { | |
constructor() { | |
this.ninjas = ['Yoshi', 'Kuma', 'Hattori']; | |
} | |
get firstNinja() { | |
console.log('Getting firstNinja'); | |
return this.ninjas[0]; | |
} | |
set firstNinja(value) { | |
console.log('Setting firstNinja'); | |
this.ninjas[0] = value; | |
} | |
} | |
const ninjaCollection = new NinjaCollection(); | |
console.log(ninjaCollection.firstNinja === 'Yoshi', 'Yoshi is the first ninja'); | |
ninjaCollection.firstNinja = 'Hachi'; | |
console.log( | |
ninjaCollection.firstNinja === 'Hachi' && ninjaCollection.ninjas[0] === 'Hachi', | |
'Now Hachi is the first ninja' | |
); |
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
const ninjaCollection = { | |
ninjas: ['Yoshi', 'Kuma', 'Hattori'], | |
get firstNinja() { | |
console.log('Getting firstNinja'); | |
return this.ninjas[0]; | |
}, | |
set firstNinja(value) { | |
console.log('Setting firstNinja'); | |
this.ninjas[0] = value; | |
} | |
}; | |
console.log(ninjaCollection.firstNinja === 'Yoshi', 'Yoshi is the first ninja'); | |
ninjaCollection.firstNinja = 'Hachi'; | |
console.log( | |
ninjaCollection.firstNinja === 'Hachi' && ninjaCollection.ninjas[0] === 'Hachi', | |
'Now Hachi is the first ninja' | |
); |
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
function Ninja() { | |
let skillLevel; | |
this.getSkillLevel = () => skillLevel; | |
this.setSkillLevel = (value) => { | |
skillLevel = value; | |
}; | |
} | |
const ninja = new Ninja(); | |
ninja.setSkillLevel(100); | |
console.log(ninja.getSkillLevel() === 100, 'Our ninja is at level 100!'); | |
console.log(ninja.skillLevel === undefined, 'And we don\'t have access for the skillLevel variable'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment