--- title: Object.prototype.toString() slug: Web/JavaScript/Reference/Global_Objects/Object/toString tags: - JavaScript - Method - Object - Prototype translation_of: Web/JavaScript/Reference/Global_Objects/Object/toString ---
{{JSRef("Global_Objects", "Object")}}

Sommario

Il metodo toString() restituisce una stringa a che rappresenta l'oggetto.

{{EmbedInteractiveExample("pages/js/object-prototype-tostring.html")}}

Sintassi

obj.toString()

Descrizione

Ogni oggetto ha un metodo toString() che è automaticamente chiamato quando l'oggetto deve essere rappresentato come valore testuale o quando l'oggetto è referenziato in un contesto in cui viene attesa una stringa. Di default, il metodo toString() è ereditato da ogni oggetto che discende da Object. Se il metodo non è sovrascritto in un oggetto personalizzato, toString() restituisce "[object type]", dove type è il tipo di oggetto. Il codice di seguito lo illustra:

var o = new Object();
o.toString();           // returns [object Object]

Nota: A partire da JavaScript 1.8.5 toString() richiamato su {{jsxref("Global_Objects/null", "null")}} restituisce [object Null], e {{jsxref("Global_Objects/undefined", "undefined")}} restituisce [object Undefined], come definito nella versione 5 di ECMAScript e nei succcessivi Errata. Vedi {{anch("Example:_Using_toString_to_detect_object_type", "Using toString to detect object type")}}.

Esempi

Esempio: Sovrascrittura del metodo di default toString 

Puoi creare una funzione che deve essere richiamata al posto del default metodo toString(). Il metodo toString() non prende argomenti e deve restituire una stringa. Esso può assumere qualunque valore tu voglia, ma sarà molto utile se comunichi informazioni sull'oggetto.

Il codice seguente definisce l'oggetto Dog e crea theDog, ovvero un oggetto di tipo Dog:

function Dog(name, breed, color, sex) {
  this.name = name;
  this.breed = breed;
  this.color = color;
  this.sex = sex;
}

theDog = new Dog('Gabby', 'Lab', 'chocolate', 'female');

Richiamando il metodo toString() su questo oggetto personalizzato, esso restituisce il valore di default ereditato da {{jsxref("Global_Objects/Object", "Object")}}:

theDog.toString(); // returns [object Object]

Il codice seguente crea e assegna il metodo dogToString() per sovrascrivere il metodo di default toString(). Questa funzione genera una stringa contenente i valori name, breed, color e sex dell'oggetto, nella forma di "property = value;".

Dog.prototype.toString = function dogToString() {
  var ret = 'Dog ' + this.name + ' is a ' + this.sex + ' ' + this.color + ' ' + this.breed;
  return ret;
}

Col precedente codice, la funzione dogToString() è richiamata automaticamente da JavaScript ogni volta che l'oggetto theDog è usato in un contesto string, e restituisce la seguente stringa:

Dog Gabby is a female chocolate Lab

Esempio: Uso di toString() per individuare l'oggetto class

toString() può essere usato con ogni oggetto e permette di ottenere il suo class. Per usare Object.prototype.toString() con ogni oggetto, c'è bisogno di richiamare {{jsxref("Function.prototype.call()")}} o {{jsxref("Function.prototype.apply()")}} su di esso, passando l'oggetto che si cerca di ispezionare come primo parametro chiamato thisArg.

var toString = Object.prototype.toString;

toString.call(new Date);    // [object Date]
toString.call(new String);  // [object String]
toString.call(Math);        // [object Math]

// Since JavaScript 1.8.5
toString.call(undefined);   // [object Undefined]
toString.call(null);        // [object Null]

Specifiche

Specifiche Stato Commento
ECMAScript 1 Edizione. Standard Definizione iniziale. Implementato in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.2.4.2', 'Object.prototype.toString')}} {{Spec2('ES5.1')}} Richiamato su {{jsxref("Global_Objects/null", "null")}} restituisce [object Null], e {{jsxref("Global_Objects/undefined", "undefined")}} restituisce [object Undefined]
{{SpecName('ES6', '#sec-object.prototype.tostring', 'Object.prototype.toString')}} {{Spec2('ES6')}}

Compatibilità browser

{{CompatibilityTable}}
Caratteristiche Chrome Firefox (Gecko) Internet Explorer Opera Safari
Support Base {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}}
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Support Base {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}}

Vedi anche