Hi,
I’m learning about the Closure, since I realize with es6 we don’t need to care anymore.
Am I right?
Do you find a context in es6 to use it?
here an exemple with es6, this code work
for (let i = 0; i < 3; i++) {
let millisecondes = i*1000
setTimeout( () => {
if (i <= 3) {
console.log(i++)
} else {
console.log('go to moon')
}
}, millisecondes )
}
es5 the same code doesn’t work
for (var i = 0; i < 3; i++) {
var millisecondes = i*1000;
setTimeout( function(){
if (i <= 3) {
console.log(i++);
} else {
console.log('go to moon');
}
}, millisecondes );
}
var planetes = ['terre', 'mars', 'venus', 'pluton'];
// button
var creerBouton = function(label) {
var btn = document.createElement('button');
btn.appendChild(document.createTextNode(label));
document.body.appendChild(btn);
return btn;
};
// create buttons and add a text
for (var h = 0; h <= 2; h++) {
var btn = creerBouton(planetes[h]);
btn.onclick = (function(h) {
return function() {
console.log('Cette super planete est '+ planete[h]);
};
})(h);
}
That makes the object only usable once, but regardless, you’re still using closures. They’re an inherent part of the language, JavaScript won’t function without them.
@PortableStick Could you tell me if this following code is a recommended way to make and access “private” properties on ES6 classes ? I knew the way you explained earlier and i’m kinda new to ES6.
I found an excellent book online: http://exploringjs.com/es6/ch_parameter-handling.html
But I don’t get for a private member, with a closure in this case but in object, I have no idea.
Edit
Do you mean a method you can only call from inside the class?
Honestly, I don’t know. I’ve used ES6 classes for React components, and made use of a babel plugin to use static properties. From what I’ve learned, I’d rather avoid the class keyword entirely and just keep using closures for private methods and properties as usual.