Skip to content

Instantly share code, notes, and snippets.

@milikkan
Created November 8, 2024 12:44
Show Gist options
  • Save milikkan/09edaf9b90e2736c2aaafa86569ae7f0 to your computer and use it in GitHub Desktop.
Save milikkan/09edaf9b90e2736c2aaafa86569ae7f0 to your computer and use it in GitHub Desktop.
JavaScript private methods with ES6 classes vs IIFE's and closure
// private methods with constructor functions without ES6 classes
const Student = (function() {
function privateMethod() {
console.log('Private method...');
}
return function(name, age) {
this.name = name;
this.age = age;
privateMethod();
}
})();
const mustafa = new Student('Mustafa', 42);
console.log(mustafa);
/*
Private method...
{ name: 'Mustafa', age: 42 }
*/
mustafa.privateMethod(); // TypeErro
// private methods with constructor functions using ES6 classes
class Student {
constructor(name, age) {
this.name = name;
this.age = age;
this.#privateMethod();
}
#privateMethod() {
console.log('Private method...');
}
}
const mustafa = new Student('Mustafa', 42);
console.log(mustafa);
/*
Private method...
{ name: 'Mustafa', age: 42 }
*/
mustafa.#privateMethod(); // SyntaxError
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment