2013-01-09 13 views
5

Sto cercando un modo per sovrascrivere la proprietà .length di un oggetto in JavaScript.Come sovrascrivere Function.length per restituire la lunghezza di un array, in modalità rigorosa

Al momento ho un wrapper su parent.properties.objects serie

(genitore viene utilizzato per il codice per essere più leggibile nel contesto)

Questa è la struttura di base:

(variabile genitore è definita nel namespace ed inizializzata)

var parent = function() { 
    this.properties = { 
    objects: []; 
    }; 
}; 

involucro

(function() { 
    "use strict"; 

    objects = function() { 

Se non viene passato alcun argomento, assumere ottenere

if (arguments.length === 0) { 
    var _objects = parent.properties.objects; 
    return _objects; 

modificare o oggetti filtro

} else if (arguments.length > 0) { 
     ... 
    } 
    }; 

questo crea un Object.prototype variabile (non [prototype]) e aggiunge la lunghezza metodo ()

objects.prototype.length = function() { 
    var length = parent.properties.objects.length; 
    return length; 
    } 

errore

012.
objects.prototype.__proto__.length = function() {  
    var length = parent.properties.objects.length; 
    return length; 
    } 

    parent.objects = objects; 
})(); 
+0

Puoi essere più specifico sul tipo di errore che stai ottenendo? – guypursey

+0

L'ho hackerato con objects.Length() (JavaScript fa distinzione tra maiuscole e minuscole). Lo sto facendo per scrivere una comoda API, e non per avere una funzione per ogni operazione get/set della proprietà. ma una singola funzione per ogni proprietà. Sarebbe stato bello chiamare objects.length(), ma objects.Length() farà, opposto a objects(). Length(). L'errore era una specie di __proto__ non trovato blah blah blah. Dovrà attendere ECMA 6. –

+0

Qual è l'ultima riga 'parent.object = object; 'cosa dovrebbe fare? 'parent' è una funzione, e non vedo una variabile' object' dichiarata ovunque – Bergi

risposta

3

Supponendo ho capito bene la tua domanda, il seguente codice potrebbe aiutare:

function MyObject() { 
    this.myActualData = []; 
} 

Object.defineProperty(MyObject.prototype, 'length', {get: function() { 
    return this.myActualData.length; 
}}); 

Ed ecco un esempio di esso in uso:

var x = new MyObject(); 
x.myActualData.push("Hello"); 
x.myActualData.push("World"); 
x.length; // is 2 

Nota: questo sarà solo il lavoro su browser ecmascript 5 e versioni successive.

+0

come posso farlo funzionare sul nome di un oggetto sconosciuto (MyObject), come se l'oggetto e il suo nome venissero creati durante il caricamento della pagina ..? –

+0

Non sono sicuro di comprendere completamente la tua domanda, ma puoi fare la chiamata a Object.defineProperty su qualsiasi oggetto, non solo su un prototipo. – kybernetikos

Problemi correlati