jQuery può essere utilizzato per analizzare gli oggetti JavaScript al fine di reperire informazioni utili su di essi. Per esempio, possiamo sapere quali sono i nomi delle proprietà, dei metodi e di eventuali altri oggetti presenti nell'oggetto ispezionato. Vediamo insieme come ottenere il nostro scopo.
Possiamo creare delle funzioni globali jQuery per ispezionare gli oggetti:
(function($) {
$.getProperties = function(obj) {
if(typeof obj !== 'object') {
throw new Error(obj + ' is not an object');
return;
}
var results = [];
for(var property in obj) {
if(obj.hasOwnProperty(property)) {
results.push(property);
}
}
return results;
};
$.getMethods = function(obj) {
if(typeof obj !== 'object') {
throw new Error(obj + ' is not an object');
return;
}
var results = [];
for(var property in obj) {
if(obj.hasOwnProperty(property)) {
if(typeof obj[property] === 'function') {
results.push(property);
}
}
}
return results;
};
$.getObjects = function(obj) {
if(typeof obj !== 'object') {
throw new Error(obj + ' is not an object');
return;
}
var results = [];
for(var property in obj) {
if(obj.hasOwnProperty(property)) {
if(typeof obj[property] === 'object') {
results.push(property);
}
}
}
return results;
};
})(jQuery);
Queste tre funzioni restituiscono ciascuna un array contenente i nomi delle proprietà, dei metodi e di eventuali altri oggetti di un oggetto passato come parametro. Vediamo il loro utilizzo.
$(function() {
var A = {
a: true,
b: function() {
return this.a;
},
c: 1,
d: {}
};
var props = $.getProperties(A);
var methods = $.getMethods(A);
var objects = $.getObjects(A);
console.log(props); // ['a', 'b', 'c', 'd']
console.log(methods); // ['b']
console.log(objects); // ['d']
});
Come si può notare, queste tre funzioni si rivelano molto utili qualora volessimo implementare una nostra reflection API con jQuery.