mozilla
Los resultados de tu búsqueda

    Object.defineProperty()

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

    Resumen

    El  método Object.defineProperty() define un a nueva propiedad directamente sobre un objecto, o modifica una propiedad existente en un objeto, y devuelve el objeto.

    Sintaxis

    Object.defineProperty(obj, prop, descriptor)

    Parámetros

    obj
    El objecto sobre el cual se define la propiedad.
    prop
    El nombre de la propiedad a ser definida o modificada.
    descriptor
    El descriptor de la propiedad que está siendo definida o modificada.

    Descripción

    Este método permite precisa adición o modificación de una propiedad de un objeto. La adición normal de una propiedad a través de la asignación crea propiedades las cuales aparecen durante la enumeración de la propiedad mediante el bucle (for...in o Object.keys método), cuyos valores pueden ser cambiados, y  los además pueden ser eliminados deleted. Este método permite que estas propiedades sean cambiadas de sus valores por defecto.

    Los descresciptores de propiedades presentes en objetos llegan en dos gustos: descriptores de datos y descriptores de acceso.  Un descriptor de datos es una propiedad que tiene un valor, el cual puede ser o no pueder escrito. Un descriptor de acceso es una propiedad descrita por un getter-setter par de funciones. Un descriptor debe de ser de uno de estos dos gustos; no puede ser ambos.

    Ambos descriptores de datos y accesores son objetos. Comparten las siguientes claves opcionales:

    configurable
    true si y solo si el tipo de descriptores de propiedad pueden ser cambiados y si la propiedad puede ser eliminada del correspondiente objeto.
    Por defecto es false.
    enumerable
    true si y solo si dicha propiedad se muestra durante la enumeración de las propiedades del objeto correspondiente.
    Por defecto es false.

    Un descriptor también tiene las siguientes claves opcionales:

    value
    The value associated with the property. Can be any valid JavaScript value (number, object, function, etc).
    Por defecto es undefined.
    writable
    true if and only if the value associated with the property may be changed with an assignment operator.
    Defaults to false.

    An accessor descriptor also has the following optional keys:

    get
    A function which serves as a getter for the property, or undefined if there is no getter. The function return will be used as the value of property.
    Defaults to undefined.
    set
    A function which serves as a setter for the property, or undefined if there is no setter. The function will receive as only argument the new value being assigned to the property.
    Defaults to undefined.

    Bear in mind that these options are not necessarily own properties so, if inherited, will be considered too. In order to ensure these defaults are preserved you might freeze the Object.prototype upfront, specify all options explicitly, or point to null as __proto__ property.

    // using __proto__
    Object.defineProperty(obj, 'key', {
      __proto__: null, // no inherited properties
      value: 'static'  // not enumerable
                       // not configurable
                       // not writable
                       // as defaults
    });
    
    // being explicit
    Object.defineProperty(obj, 'key', {
      enumerable: false,
      configurable: false,
      writable: false,
      value: 'static'
    });
    
    // recycling same object
    function withValue(value) {
      var d = withValue.d || (
        withValue.d = {
          enumerable: false,
          writable: false,
          configurable: false,
          value: null
        }
      );
      d.value = value;
      return d;
    }
    // ... and ...
    Object.defineProperty(obj, 'key', withValue('static'));
    
    // if freeze is available, prevents the code to add
    // value, get, set, enumerable, writable, configurable
    // to the Object prototype
    (Object.freeze || Object)(Object.prototype);
    

    Examples

    If you want to see how to use the Object.defineProperty method with a binary-flags-like syntax, see additional examples.

    Example: Creating a property

    When the property specified doesn't exist in the object, Object.defineProperty() creates a new property as described. Fields may be omitted from the descriptor, and default values for those fields are imputed. All of the Boolean-valued fields default to false. The value, get, and set fields default to undefined. A property which is defined without get/set/value/writable is called “generic” and is “typed” as a data descriptor.

    var o = {}; // Creates a new object
    
    // Example of an object property added with defineProperty with a data property descriptor
    Object.defineProperty(o, 'a', {
      value: 37,
      writable: true,
      enumerable: true,
      configurable: true
    });
    // 'a' property exists in the o object and its value is 37
    
    // Example of an object property added with defineProperty with an accessor property descriptor
    var bValue = 38;
    Object.defineProperty(o, 'b', {
      get: function() { return bValue; },
      set: function(newValue) { bValue = newValue; },
      enumerable: true,
      configurable: true
    });
    o.b; // 38
    // 'b' property exists in the o object and its value is 38
    // The value of o.b is now always identical to bValue, unless o.b is redefined
    
    // You cannot try to mix both:
    Object.defineProperty(o, 'conflict', {
      value: 0x9f91102,
      get: function() { return 0xdeadbeef; }
    });
    // throws a TypeError: value appears only in data descriptors, get appears only in accessor descriptors
    

    Example: Modifying a property

    When the property already exists, Object.defineProperty() attempts to modify the property according to the values in the descriptor and the object's current configuration. If the old descriptor had its configurable attribute set to false (the property is said to be “non-configurable”), then no attribute besides writable can be changed. In that case, it is also not possible to switch back and forth between the data and accessor property types.

    If a property is non-configurable, its writable attribute can only be changed to false.

    A TypeError is thrown when attempts are made to change non-configurable property attributes (besides the writable attribute) unless the current and new values are the same.

    Writable attribute

    When the writable property attribute is set to false, the property is said to be “non-writable”. It cannot be reassigned.

    var o = {}; // Creates a new object
    
    Object.defineProperty(o, 'a', {
      value: 37,
      writable: false
    });
    
    console.log(o.a); // logs 37
    o.a = 25; // No error thrown (it would throw in strict mode, even if the value had been the same)
    console.log(o.a); // logs 37. The assignment didn't work.
    

    As seen in the example, trying to write into the non-writable property doesn't change it but doesn't throw an error either.

    Enumerable attribute

    The enumerable property attribute defines whether the property shows up in a for...in loop and Object.keys() or not.

    var o = {};
    Object.defineProperty(o, 'a', { value: 1, enumerable: true });
    Object.defineProperty(o, 'b', { value: 2, enumerable: false });
    Object.defineProperty(o, 'c', { value: 3 }); // enumerable defaults to false
    o.d = 4; // enumerable defaults to true when creating a property by setting it
    
    for (var i in o) {
      console.log(i);
    }
    // logs 'a' and 'd' (in undefined order)
    
    Object.keys(o); // ['a', 'd']
    
    o.propertyIsEnumerable('a'); // true
    o.propertyIsEnumerable('b'); // false
    o.propertyIsEnumerable('c'); // false
    

    Configurable attribute

    The configurable attribute controls at the same time whether the property can be deleted from the object and whether its attributes (other than writable) can be changed.

    var o = {};
    Object.defineProperty(o, 'a', {
      get: function() { return 1; },
      configurable: false
    });
    
    Object.defineProperty(o, 'a', { configurable: true }); // throws a TypeError
    Object.defineProperty(o, 'a', { enumerable: true }); // throws a TypeError
    Object.defineProperty(o, 'a', { set: function() {} }); // throws a TypeError (set was undefined previously)
    Object.defineProperty(o, 'a', { get: function() { return 1; } }); // throws a TypeError (even though the new get does exactly the same thing)
    Object.defineProperty(o, 'a', { value: 12 }); // throws a TypeError
    
    console.log(o.a); // logs 1
    delete o.a; // Nothing happens
    console.log(o.a); // logs 1
    

    If the configurable attribute of o.a had been true, none of the errors would be thrown and the property would be deleted at the end.

    Example: Adding properties and default values

    It's important to consider the way default values of attributes are applied. There is often a difference between simply using dot notation to assign a value and using Object.defineProperty(), as shown in the example below.

    var o = {};
    
    o.a = 1;
    // is equivalent to:
    Object.defineProperty(o, 'a', {
      value: 1,
      writable: true,
      configurable: true,
      enumerable: true
    });
    
    
    // On the other hand,
    Object.defineProperty(o, 'a', { value: 1 });
    // is equivalent to:
    Object.defineProperty(o, 'a', {
      value: 1,
      writable: false,
      configurable: false,
      enumerable: false
    });
    

    Example: Custom Setters and Getters

    Example below shows how to implement a self-archiving object. When temperature property is set, the archive array gets a log entry.

    function Archiver() {
      var temperature = null;
      var archive = [];
    
      Object.defineProperty(this, 'temperature', {
        get: function() {
          console.log('get!');
          return temperature;
        },
        set: function(value) {
          temperature = value;
          archive.push({ val: temperature });
        }
      });
    
      this.getArchive = function() { return archive; };
    }
    
    var arc = new Archiver();
    arc.temperature; // 'get!'
    arc.temperature = 11;
    arc.temperature = 13;
    arc.getArchive(); // [{ val: 11 }, { val: 13 }]
    

    Especificaciones

    Specification Status Comment
    ECMAScript 5.1 (ECMA-262)
    The definition of 'Object.defineProperty' in that specification.
    Standard Initial definition. Implemented in JavaScript 1.8.5.
    ECMAScript 6 (ECMA-262)
    The definition of 'Object.defineProperty' in that specification.
    Draft  

    Compatibilidad con navegadores

    Help improve compatibility tables by filling out this 11 question survey.
    Característica Firefox (Gecko) Chrome Internet Explorer Opera Safari
    Soporte Básico 4.0 (2) 5 (versiones previas sin testear) 9 (8, pero solo con objetos DOM y con muchos comportamientos no estándares  See below.) 11.60 5.1 (5, but not on DOM objects)
    Característica Firefox Mobile (Gecko) Android IE Mobile Opera Mobile Safari Mobile
    Soporte Básico 4.0 (2) (Yes) 9 and above 11.50 (Yes)

    Based on Kangax's compat tables.

    Redefining the length property of an Array object

    It is possible to redefine the length property of arrays, subject to the usual redefinition restrictions. (The length property is initially non-configurable, non-enumerable, and writable. Thus on an unaltered array it is possible to change the length property's value, or to make it non-writable. It is not allowed to change its enumerability or configurability, or if it is non-writable to change its value or writability.) However, not all browsers permit this redefinition.

    Firefox 4 through 22 will throw a TypeError on any attempt whatsoever (whether permitted or not) to redefine the length property of an array.

    Versions of Chrome which implement Object.defineProperty() in some circumstances ignore a length value different from the array's current length property. In some circumstances changing writability seems to silently not work (and not throw an exception). Also, relatedly, some array-mutating methods like Array.prototype.push don't respect a non-writable length.

    Versions of Safari which implement Object.defineProperty() ignore a length value different from the array's current length property, and attempts to change writability execute without error but do not actually change the property's writability.

    Only Internet Explorer 9 and later, and Firefox 23 and later, appear to fully and correctly implement redefinition of the length property of arrays. For now, don't rely on redefining the length property of an array to either work, or to work in a particular manner. And even when you can rely on it, there's really no good reason to do so.

    Internet Explorer 8 specific notes

    Internet Explorer 8 implemented a Object.defineProperty() method that could only be used on DOM objects. A few things need to be noted:

    • Trying to use Object.defineProperty() on native objects throws an error.
    • Property attributes must be set to some values. true, true, true for data descriptor and true for configurable, false for enumerable for accessor descriptor.(?) Any attempt to provide other value(?) will result in an error being thrown.
    • Reconfiguring a property requires first deleting the property. If the property isn't deleted, it stays as it was before the reconfiguration attempt.

    See also

    Etiquetas y colaboradores del documento

    Contributors to this page: Siro_Diaz
    Última actualización por: Siro_Diaz,