function Temp() {
return {
setHot: function(v) { this.hot=v },
getHot: function() { return this.hot; },
hot: false
}
}
var w = new Temp();
w.setHot(true);
w.hot !== w.getHot()
Questo, credo, s quello che avresti bisogno di fare per farlo funzionare. Non c'è affatto bisogno di isHot var. I metodi get set modificano direttamente il valore caldo degli oggetti, il che significa che getHot() e w.hot restituiranno il valore corretto.
Se si desidera rendere privato il valore isHot, quindi credo che sarà necessario utilizzare isHot var, ma non sarebbe necessario o fare riferimento al valore di w.hot. Non sono sicuro quali sarebbero le conseguenze di tale azione.
function Temp() {
var isHot = false;
return {
setHot: function(v) { isHot=v },
getHot: function() { return isHot; }
}
}
var w = new Temp();
w.setHot(true);
w.getHot();
However you can not access w.isHot, essentially private var.
Articoli correlati forse ..
E se crei un'altra istanza di 'Temp', ti confonderai per giorni chiedendoti perché quando si imposta" setHot (true) "su un'istanza imposta' getHot() 'su' true' su tutte le istanze. Non esistono variabili di istanze private in JavaScript senza un pessimo hacker (come l'esempio di 'WeakMap' nel link che hai fornito). – Adam
ha ha, si, questo è un ottimo punto! Sentiti libero di modificare il post per rendere quel punto più pertinente. – Emile