Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Treballar amb Objectes

This translation is incomplete. Please help translate this article from English.

JavaScript està dissenyat en un simple paradigma basat en objectes. Un objecte és una col·lecció de propietats, i una propietat és una associació entre un nom i un valor. Un valor d'una propietat pot ser una funció, en aquest cas la propietat es coneix com a mètode. A més a més dels objectes que estan predefinits en el navegador, també es pot definir objectes propis.

Resum d'objectes

Els objects en JavaScript, com també passa en altres llenguatges de programació, poden comparar-se a objectes en la vida real. El concepte d'objectes en JavaScript pot ser entès amb la vida real, amb objectes tangibles.

A JavaScript, un objecte és una entitat independent, amb propietats i tipus. Ho podeu comparar amb una tassa, per exemple. Una tassa és un objecte, amb propietats. Una tassa té un color, un disseny, un pes, un material del qual està fet, etc. De la mateixa manera, els objectes en JavaScript poden tenir propietats, que defineixen les seves característiques.

Objectes i propietats

Un objecte de JavaScript té unes porpietats associades. Una propietat d'un objecte pot explicar-se com una variable que està lligada a l'objecte. Les propietats d'un objecte són bàsicament el mateix que variables comunes de JavaScript, excepte per la lligadura als objectes. Les propietats d'un objecte defineixen les característiques de l'objecte. Es pot accedir a les propietats d'un objecte amb un simple punt:

objectName.propertyName

Com totes les variables a JavaScript, tant en el nom de l'objecte (que pot ser una variable normal) com en el nom de la propietat és distingeix entre majúscules i minúscules. Es pot definir una propietat assignant-li un valor. Per exemple, creem un objecte anomenat myCar i li donem propietats anomenades make, model, i year com s'indica a continuació:

var myCar = new Object();
myCar.make = "Ford";
myCar.model = "Mustang";
myCar.year = 1969;

També es pot accedir o assignar propietats dels objectes de JavaScriptor fent ús de claudàtors. Algunes vegades els objectes són anomenats arrays d'associació, ja que cada propietat és associada amb un valor de tipus cadena que es pot fer servir per accedir-hi. Així, per exemple, es podria accedir a les propietats de l'obejcte myCar com s'indica a continuació:

myCar["make"] = "Ford";
myCar["model"] = "Mustang";
myCar["year"] = 1969;

Un nom d'una propietat d'un objecte pot ser quasevol cadena vàlida de JavaScript, o qualsevol cosa que es pugui convertir a una cadena, incloent la cadena buida. tanmateix, qualsevol nom d'una propietat que no és un identificador vàlid de JavaScript (per exemple, un nom d'una propietat que té un espai o un guió, o que comenci amb un nombre) només es pot accedir-hi usant la notació claudàtors. Aquesta notació és també molt útil per quan els noms de les propietats s'han de determinar dinàmicament (quan el nom d'una propietat no és determina fins que entra en execució). Alguns exemples a continuació:

var myObj = new Object(),
    str = "myString",
    rand = Math.random(),
    obj = new Object();      // quatre variables són creades i assignades d'un sol cop, separades per comes

myObj.type              = "Dot syntax";
myObj["date created"]   = "String with space";
myObj[str]              = "String value";
myObj[rand]             = "Random Number";
myObj[obj]              = "Object";
myObj[""]               = "Even an empty string";

console.log(myObj);

També es pot accedir a les propietats mitjançant l'ús d'un valor de cadena que s'emmagatzema en una variable:

var propertyName = "make";
myCar[propertyName] = "Ford";

propertyName = "model";
myCar[propertyName] = "Mustang";

Es pot fer servir la notació claudàtors amb for...in per iterar sobre totes les propietats enumerables d'un objecte. Per il·lustrar com funciona això, la següent funció mostra les propietats de l'objecte quan es pasa l'objecte i el nom de l'objecte com a arguments de la funció:

function showProps(obj, objName) {
  var result = "";
  for (var i in obj) {
    if (obj.hasOwnProperty(i)) {
        result += objName + "." + i + " = " + obj[i] + "\n";
    }
  }
  return result;
}

Així, la crida de la funció showProps(myCar, "myCar") retornaria el següent:

myCar.make = Ford
myCar.model = Mustang
myCar.year = 1969

Objecte tot

A JavaScript, quasi tot és un objecte. Tots els tipus primitius excepte null i undefined són tractats com a objectes. Se'ls hi poden assignar propietats (les propietats assignades d'alguns tipus no són persistents), i tenen totes les característiques dels objectes.

Enumerar totes les propietats d'un objecte

A partir de ECMAScript 5, hi ha tres formes bàsiques per llistar/recòrrer propietats d'un objecte:

  • Bucle for...in
    Aquest mètode recorre totes les propietats numerables d'un objecte i la seva cadena prototip.
  • Object.keys(o)
    Aquest mètode retorna una array amb tots els noms de els propietats enumerables ("keys") pròpies (no en la cadena prototip)  d'un objecte o.
  • Object.getOwnPropertyNames(o)
    Aquest mètode retorna una array que conté tots els noms de les propietats pròpies (enumerables o no) d'un objecte o.

Abans de ECMAScript 5, no hi havia cap forma original de llistar totes les propietats d'un objecte. Tanmateix, això es pot aconseguir amb la funció següent:

function listAllProperties(o){     
	var objectToInspect;     
	var result = [];
	
	for(objectToInspect = o; objectToInspect !== null; objectToInspect = Object.getPrototypeOf(objectToInspect)){  
		result = result.concat(Object.getOwnPropertyNames(objectToInspect));  
	}
	
	return result; 
}

Això pot ser útil per revelar propietats "amagades" (propietats en la cadena prototip que no són accessibles a través de l'objecte, ja que una altra propietat té el mateix nom abans en la cadena prototip). Llistar les propietats accessibles només es pot fer de forma simple per mitjà d'eliminar les dupliques de l'array.

Crear nous objectes

JavaScript té un nombre d'objectes predefinits. A més a més, també es pot crear els objectes propis. A partir de JavaScript 1.2r, es pot crear un objecte usant un objecte inicialitzador. Alternativament, primer es pot crear una funció constructora i després una instància de l'objecte fent servir aquesta funció i l'operador new.

Utilitzar inicialitzadors d'objectes

A més a més de poder crear objectes per mitjà de la funció constructora, es pot crear objectes fent servir un inicialitzador d'objectes. Utilitzar inicialitzadors d'objectes en alguns casos fa referència a crear objectes amb notació literal. "Inicialitzador d'un objecte" és coherent amb la terminologia utilitzada per C++.

La sintaxi per un objecte mitjançant un inicialitzador d'objectes és:

var obj = { property_1:   value_1,   // la propietat_# pot ser un identificador...
            2:            value_2,   // o un nombre...
            // ...,
            "property n": value_n }; // o una cadena

On obj és el nom del nou objecte, cada property_i és un identificador (ja sigui un nom, un nombre, o una cadena literal), i cada value_i és una expressió la qual el seu valor és assignat a la property_i. L'obj i l'assignació és opcional; si no cal referir-se a ella en cap altre lloc no fa falta assignar-la a una variable. (Tingueu en compte que podeu necessitar embolcallar l'objecte literal entre parèntesis si l'objecte apareix en el lloc on s'espera una sentència, per tal de no confondre el literal amb una sentència de bloc.)

Els inicialitzadors d'objectes són expressionss, i cada inicialitzador d'objectes resulta en un nou objecte que es crea cada vegada que s'executa la sentència on apareix. Els inicialitzadors d'objectes idèntics creen objectes diferents que no es comparen entre ells com a iguals. Els objectes es creen com si es fes una crida a new Object(); és a dir, els objectes creats d'expressions literals d'objectes són instàncies d'Object.

La següent sentència crea un objecte i l'assigna a la variable x si i només si l'expressió cond és certa:

if (cond) var x = {hi: "there"};

L'exemple següent crea myHonda amb tres propietats. Vegeu que la propietat engine és també un objecte amb les seves pròpies propietats.

var myHonda = {color: "red", wheels: 4, engine: {cylinders: 4, size: 2.2}};

També es pot fer servir inicialitzadors d'objectes per crear arrays. Vegeu array literals.

En JavaScript 1.1 i en versions interiors, no es pot fer servir inicialitzadors d'objectes. Es pot crear objectes usant només les seves funcions constructores o utilitzant una funció subministrada per algun altre objecte per aquest objectiu. Vegeu Using a constructor function.

Utilitzar una funció constructora

Alternativament, es pot crear un objecte amb aquests dos pasos:

  1. Definir el tipus d'objecte escrivint una funció constructora. Hi ha una forta convenció, amb bones raons, d'utilitzar una majúscula com a primera lletra.
  2. Crear una instància de l'objecte amb new.

Per definir un tipus d'objecte, es crea una funció pel tipus d'objecte que especifiqui el nom, les propietats, i els mètodes. Per exemple, suposeu que voleu crear un tipus d'objecte per cotxes. Voleu que aquest tipus d'objecte s'anomeni car, i voleu que tingui les propietats per marca, model, i any. Per fer això, escriurieu la funció següent:

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}

Observeu l'ús de this per assignar valors a les propietats de l'objecte en funció dels valors passats a la funció.

Ara podeu crear un objecte anomenat mycar de la forma següent:

var mycar = new Car("Eagle", "Talon TSi", 1993);

Aquesta sentència crea mycar i li assigna els valors especificats per les seves propietats. Llavors el valor de mycar.make és la cadena "Eagle", mycar.year és el nombre enter 1993, i així successivament.

Es pot crear qualsevol nombre d'objectes de car mitjançant crides a new. Per exemple,

var kenscar = new Car("Nissan", "300ZX", 1992);
var vpgscar = new Car("Mazda", "Miata", 1990);

Un objecte pot tenir una propietat que per ella mateixa sigui un altre objecte. Per exemple, suposeu que definiu un objecte anomenat person de la forma següent:

function Person(name, age, sex) {
  this.name = name;
  this.age = age;
  this.sex = sex;
}

I despres creeu dues noves instàncies de l'objecte person de la forma següent:

var rand = new Person("Rand McKinnon", 33, "M");
var ken = new Person("Ken Jones", 39, "M");

Llavors, podeu reescriure la definició de car per incloure una propietat d'owner que pren un objecte person, com es fa de la forma següent:

function Car(make, model, year, owner) {
  this.make = make;
  this.model = model;
  this.year = year;
  this.owner = owner;
}

Per crear instàncies de nous objectes, s'utilitza el següent:

var car1 = new Car("Eagle", "Talon TSi", 1993, rand);
var car2 = new Car("Nissan", "300ZX", 1992, ken);

Notice that instead of passing a literal string or integer value when creating the new objects, the above statements pass the objects rand and ken as the arguments for the owners. Then if you want to find out the name of the owner of car2, you can access the following property:

car2.owner.name

Note that you can always add a property to a previously defined object. For example, the statement

car1.color = "black";

adds a property color to car1, and assigns it a value of "black." However, this does not affect any other objects. To add the new property to all objects of the same type, you have to add the property to the definition of the car object type.

Using the Object.create method

Objects can also be created using the Object.create method. This method can be very useful, because it allows you to choose the prototype object for the object you want to create, without having to define a constructor function. For more detailed information on the method and how to use it, see Object.create method.

// Animal properties and method encapsulation
var Animal = {
  type: "Invertebrates", // Default value of properties
  displayType : function(){  // Method which will display type of Animal
    console.log(this.type);
  }
}

// Create new animal type called animal1 
var animal1 = Object.create(Animal);
animal1.displayType(); // Output:Invertebrates

// Create new animal type called Fishes
var fish = Object.create(Animal);
fish.type = "Fishes";
fish.displayType(); // Output:Fishes

Inheritance

All objects in JavaScript inherit from at least one other object. The object being inherited from is known as the prototype, and the inherited properties can be found in the prototype object of the constructor.

Indexing object properties

In JavaScript 1.0, you can refer to a property of an object either by its property name or by its ordinal index. In JavaScript 1.1 and later, however, if you initially define a property by its name, you must always refer to it by its name, and if you initially define a property by an index, you must always refer to it by its index.

This restriction applies when you create an object and its properties with a constructor function (as we did previously with the Car object type) and when you define individual properties explicitly (for example, myCar.color = "red"). If you initially define an object property with an index, such as myCar[5] = "25 mpg", you can subsequently refer to the property only as myCar[5].

The exception to this rule is objects reflected from HTML, such as the forms array. You can always refer to objects in these arrays by either their ordinal number (based on where they appear in the document) or their name (if defined). For example, if the second <FORM> tag in a document has a NAME attribute of "myForm", you can refer to the form as document.forms[1] or document.forms["myForm"] or document.myForm.

Defining properties for an object type

You can add a property to a previously defined object type by using the prototype property. This defines a property that is shared by all objects of the specified type, rather than by just one instance of the object. The following code adds a color property to all objects of type car, and then assigns a value to the color property of the object car1.

Car.prototype.color = null;
car1.color = "black";

See the prototype property of the Function object in the JavaScript Reference for more information.

Defining methods

A method is a function associated with an object, or, simply put, a method is a property of an object that is a function. Methods are defined the way normal functions are defined, except that they have to be assigned as the property of an object. Examples are:

objectName.methodname = function_name;

var myObj = {
  myMethod: function(params) {
    // ...do something
  }
};

where objectName is an existing object, methodname is the name you are assigning to the method, and function_name is the name of the function.

You can then call the method in the context of the object as follows:

object.methodname(params);

You can define methods for an object type by including a method definition in the object constructor function. For example, you could define a function that would format and display the properties of the previously-defined car objects; for example,

function displayCar() {
  var result = "A Beautiful " + this.year + " " + this.make
    + " " + this.model;
  pretty_print(result);
}

where pretty_print is a function to display a horizontal rule and a string. Notice the use of this to refer to the object to which the method belongs.

You can make this function a method of car by adding the statement

this.displayCar = displayCar;

to the object definition. So, the full definition of car would now look like

function Car(make, model, year, owner) {
  this.make = make;
  this.model = model;
  this.year = year;
  this.owner = owner;
  this.displayCar = displayCar;
}

Then you can call the displayCar method for each of the objects as follows:

car1.displayCar();
car2.displayCar();

This produces the output shown in the following figure.

Image:obja.gif

Figure 7.1: Displaying method output.

Using this for object references

JavaScript has a special keyword, this, that you can use within a method to refer to the current object. For example, suppose you have a function called validate that validates an object's value property, given the object and the high and low values:

function validate(obj, lowval, hival) {
  if ((obj.value < lowval) || (obj.value > hival))
    alert("Invalid Value!");
}

Then, you could call validate in each form element's onchange event handler, using this to pass it the element, as in the following example:

<input type="text" name="age" size="3"
  onChange="validate(this, 18, 99)">

In general, this refers to the calling object in a method.

When combined with the form property, this can refer to the current object's parent form. In the following example, the form myForm contains a Text object and a button. When the user clicks the button, the value of the Text object is set to the form's name. The button's onclick event handler uses this.form to refer to the parent form, myForm.

<form name="myForm">
<p><label>Form name:<input type="text" name="text1" value="Beluga"></label>
<p><input name="button1" type="button" value="Show Form Name"
     onclick="this.form.text1.value = this.form.name">
</p>
</form>

Defining getters and setters

A getter is a method that gets the value of a specific property. A setter is a method that sets the value of a specific property. You can define getters and setters on any predefined core object or user-defined object that supports the addition of new properties. The syntax for defining getters and setters uses the object literal syntax.

JavaScript 1.8.1 note

Starting in JavaScript 1.8.1, setters are no longer called when setting properties in object and array initializers.

The following JS shell session illustrates how getters and setters could work for a user-defined object o. The JS shell is an application that allows developers to test JavaScript code in batch mode or interactively. In Firefox you can get a JS shell by pressing Ctrl+Shift+K.

js> var o = {a: 7, get b() {return this.a + 1;}, set c(x) {this.a = x / 2}};
[object Object]
js> o.a;
7
js> o.b;
8
js> o.c = 50;
js> o.a;
25

The o object's properties are:

  • o.a — a number
  • o.b — a getter that returns o.a plus 1
  • o.c — a setter that sets the value of o.a to half of the value o.c is being set to

Please note that function names of getters and setters defined in an object literal using "[gs]et property()" (as opposed to __define[GS]etter__ ) are not the names of the getters themselves, even though the [gs]et propertyName(){ } syntax may mislead you to think otherwise. To name a function in a getter or setter using the "[gs]et property()" syntax, define an explicitly named function programmatically using Object.defineProperty (or the Object.prototype.__defineGetter__ legacy fallback).

This JavaScript shell session illustrates how getters and setters can extend the Date prototype to add a year property to all instances of the predefined Date class. It uses the Date class's existing getFullYear and setFullYear methods to support the year property's getter and setter.

These statements define a getter and setter for the year property:

js> var d = Date.prototype;
js> Object.defineProperty(d, "year", {
    get: function() {return this.getFullYear() },
    set: function(y) { this.setFullYear(y) }
});

These statements use the getter and setter in a Date object:

js> var now = new Date;
js> print(now.year);
2000
js> now.year = 2001;
987617605170
js> print(now);
Wed Apr 18 11:13:25 GMT-0700 (Pacific Daylight Time) 2001

Obsolete syntaxes

In the past, JavaScript supported several other syntaxes for defining getters and setters. None of these syntaxes were supported by other engines, and support has been removed in recent versions of JavaScript. See this dissection of the removed syntaxes for further details on what was removed and how to adapt to those removals.

Summary

In principle, getters and setters can be either

  • defined using object initializers, or
  • added later to any object at any time using a getter or setter adding method.

When defining getters and setters using object initializers all you need to do is to prefix a getter method with get and a setter method with set. Of course, the getter method must not expect a parameter, while the setter method expects exactly one parameter (the new value to set). For instance:

var o = {
  a: 7,
  get b() { return this.a + 1; },
  set c(x) { this.a = x / 2; }
};

Getters and setters can also be added to an object at any time after creation using the Object.defineProperties method. This method's first parameter is the object on which you want to define the getter or setter. The second parameter is an object whose property names are the getter or setter names, and whose property values are objects for defining the getter or setter functions. Here's an example that defines the same getter and setter used in the previous example:
 

var o = { a:0 }

Object.defineProperties(o, {
    "b": { get: function () { return this.a + 1; } },
    "c": { set: function (x) { this.a = x / 2; } }
});

o.c = 10 // Runs the setter, which assigns 10 / 2 (5) to the 'a' property
console.log(o.b) // Runs the getter, which yields a + 1 or 6

Which of the two forms to choose depends on your programming style and task at hand. If you already go for the object initializer when defining a prototype you will probably most of the time choose the first form. This form is more compact and natural. However, if you need to add getters and setters later — because you did not write the prototype or particular object — then the second form is the only possible form. The second form probably best represents the dynamic nature of JavaScript — but it can make the code hard to read and understand.

Prior to Firefox 3.0, getter and setter are not supported for DOM Elements. Older versions of Firefox silently fail. If exceptions are needed for those, changing the prototype of HTMLElement (HTMLElement.prototype.__define[SG]etter__) and throwing an exception is a workaround.

With Firefox 3.0, defining getter or setter on an already-defined property will throw an exception. The property must be deleted beforehand, which is not the case for older versions of Firefox.

Vegeu també

Eliminar propietats

You can remove a non-inherited property by using the delete operator. The following code shows how to remove a property.

//Creates a new object, myobj, with two properties, a and b.
var myobj = new Object;
myobj.a = 5;
myobj.b = 12;

//Removes the a property, leaving myobj with only the b property.
delete myobj.a;
console.log ("a" in myobj) // yields "false"

You can also use delete to delete a global variable if the var keyword was not used to declare the variable:

g = 17;
delete g;

See delete for more information.

Comparar Objectes

In JavaScript objects are a reference type. Two distinct objects are never equal, even if they have the same properties. Only comparing the same object reference with itself yields true.

// Two variables, two distict objects with the same properties
var fruit = {name: "apple"};
var fruitbear = {name: "apple"};

fruit == fruitbear // return false
fruit === fruitbear // return false
// Two variables, a single object
var fruit = {name: "apple"};
var fruitbear = fruit;  // assign fruit object reference to fruitbear

// here fruit and fruitbear are pointing to same object
fruit == fruitbear // return true
fruit === fruitbear // return true

Per més informació sobre els operadors de comparació, vegeu operadors de comparació.

Vegeu també

Document Tags and Contributors

 Contributors to this page: jigs12, fscholz, llue
 Last updated by: jigs12,