Created
November 8, 2024 12:44
-
-
Save milikkan/09edaf9b90e2736c2aaafa86569ae7f0 to your computer and use it in GitHub Desktop.
JavaScript private methods with ES6 classes vs IIFE's and closure
This file contains 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
// 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 |
This file contains 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
// 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