Beh, ho cercato di capire che questo è possibile in qualsiasi modo. Ecco il codice:Javascript membro privato su prototipo
a=function(text)
{
var b=text;
if (!arguments.callee.prototype.get)
arguments.callee.prototype.get=function()
{
return b;
}
else
alert('already created!');
}
var c=new a("test"); // creates prototype instance of getter
var d=new a("ojoj"); // alerts already created
alert(c.get()) // alerts test
alert(d.get()) // alerts test from context of creating prototype function :(
Come vedi ho cercato di creare prototipi getter. Per cosa? Beh, se si scrive qualcosa di simile:
a=function(text)
{
var b=text;
this.getText=function(){ return b}
}
... tutto dovrebbe andare bene .. ma in realtà ogni volta che creare l'oggetto - creo funzione getText che utilizza la memoria. Mi piacerebbe avere una funzione prototipo che giace nella memoria che farebbe lo stesso ... Qualche idea?
EDIT:
ho provato soluzione proposta dal Christoph, e sembra che la sua soluzione nota solo per ora. È necessario ricordare le informazioni sull'ID per recuperare il valore dal contesto, ma l'intera idea è piacevole per me :) L'id è solo una cosa da ricordare, tutto il resto può essere memorizzato una volta nella memoria. In effetti è possibile memorizzare un sacco di membri privati in questo modo e utilizzare sempre un solo ID. In realtà questo mi sta soddisfacendo :) (a meno che qualcuno non abbia un'idea migliore).
someFunc = function()
{
var store = new Array();
var guid=0;
var someFunc = function(text)
{
this.__guid=guid;
store[guid++]=text;
}
someFunc.prototype.getValue=function()
{
return store[this.__guid];
}
return someFunc;
}()
a=new someFunc("test");
b=new someFunc("test2");
alert(a.getValue());
alert(b.getValue());
questo sembra un duplicato di [un'altra domanda] (http://stackoverflow.com/questions/436120) –