|
|
|
![]() |
|
Strumenti |
![]() |
#1 |
Senior Member
Iscritto dal: Dec 2002
Messaggi: 3359
|
[javascript]mootools classi con variabili private
Salve, stavo cercando come realizzare una classe in mootools con variabili e metodi privati e ho trovato dei "mutator" adatti allo scopo.
Sfortunatamente gli ho provati tutti ma nessuno sembra fare quello che affermano... Probabilmente sbaglio io, quindi vi chiedo se gentilmente potete provare questi esempi e dirmi se funzionano davvero, cioè se realmente le variabili private non sono accessibili dall'esterno. 1) Codice:
Class.Mutators.Privates = function(self, privates) { delete self['Privates']; var oldInit = self.initialize; self.initialize = function() { var tempThis = $unlink(this); var instPriv = $unlink(privates); var instance = oldInit.apply(tempThis,arguments); for(var prop in tempThis) { if(instPriv.hasOwnProperty(prop)) { instPriv[prop] = tempThis[prop]; } else { this[prop] = tempThis[prop]; } } var that = this; for(var key in tempThis) { if($type(tempThis[key]) === 'function' && key !== 'initialize') { (function (fn) { var oldProp = that[key]; that[fn] = function() { var my = $merge(that, instPriv); var bound = oldProp.bind(my,arguments); var returns = bound(); for(var prop in my) { if(instPriv.hasOwnProperty(prop) && $type(instPriv[prop] !== 'function')) { instPriv[prop] = my[prop]; } else { that[prop] = my[prop]; } } return returns; }; })(key); } } return instance; } return self; }; var Secret = new Class({ Implements: [Options, Events], Privates: { secret: 'shhhh' }, open: null, initialize: function(word) { this.secret = word; this.open = 'not a secret'; }, getSecret: function() { return this.secret; }, setSecret: function(newWord) { this.secret = newWord; this.notSecret = 'im a new prop in this'; }, getOpen: function() { return this.open; } }); var test = new Secret('this a secret test'); test.open test.secret //mi risulta accessibile ma non dovrebbe... Codice:
Class.Mutators.Privates = function(self,properties){ var priv = {}; $splat(properties).each(function(property){ priv[property] = self[property]; }); self.initalize = (function(){ for(prop in priv){ this[prop] = priv[prop]; self[prop] = undefined; } return self.initialize; })(); } var Secret = new Class({ Privates : ['secret'], secret : 'hidden message', getSecret : function(){ return secret; } }); var msg = new Secret(); msg.getSecret(); // returns "hidden message" <- errore, secret non è definito msg.secret; // returns undefined <- a me risulta accessibile... Non ho mai usato mootools(e nemmo ho intenzione di farlo), ma sono curioso di vedere il risultato di qusto framework. |
![]() |
![]() |
![]() |
Strumenti | |
|
|
Tutti gli orari sono GMT +1. Ora sono le: 06:09.