Skip to content

Instantly share code, notes, and snippets.

@munkacsitomi
Last active February 26, 2020 17:54
Show Gist options
  • Save munkacsitomi/7f8b255b28cda247973dfa947e1fb7c9 to your computer and use it in GitHub Desktop.
Save munkacsitomi/7f8b255b28cda247973dfa947e1fb7c9 to your computer and use it in GitHub Desktop.
Getter/Setter methods in JS
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'
);
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'
);
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