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.

Object.create()

Resumen

El método Object.create() crea un nuevo objeto con el objeto y propiedades del prototipo especificado.

Sintaxis

Object.create(proto [, propertiesObject ])

Parámetros

proto
Objeto el cual debe ser el prototipo del nuevo objeto recien creado.
propertiesObject
Si se especifica y no es undefined, un objeto cuyas propiedades enumerables propias (es decir, aquellas propiedades definidas sobre si mismo y no son propiedades enumerable a lo largo de su cadena de prototipos) espefica descriptores de propiedad para ser agregadas al objeto recien creado, con los nombres de propiedad correspondiente. Estas propiedades corresponden al segundo argumento de  Object.defineProperties.

Lanza

Lanza una excepción TypeError si el parámetro proto no es null o un objeto.

Ejemplos

Herencia clásica con Object.create

Debajo esta un ejemplo de como usar Object.create para lograr herencia clásica. Esta es para herencía simple, la cual es todo lo que soporta JavaScript.

// Shape - superclase
function Shape() {
  this.x = 0;
  this.y = 0;
}

// método de la superclase
Shape.prototype.move = function(x, y) {
    this.x += x;
    this.y += y;
    console.info("Shape moved.");
};

// Rectangle - subclase
function Rectangle() {
  Shape.call(this); // llama al contructor de la superclase.
}

// subclase extiende superclase
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;

var rect = new Rectangle();

rect instanceof Rectangle // true.
rect instanceof Shape // true.

rect.move(1, 1); // Salida, "Shape moved."

Si desea heredar desde multiples objetos, entonces los mixins son una posibilidad.

function MyClass() {
     SuperClass.call(this);
     OtherSuperClass.call(this);
}

MyClass.prototype = Object.create(SuperClass.prototype); // inherit
mixin(MyClass.prototype, OtherSuperClass.prototype); // mixin

MyClass.prototype.myMethod = function() {
     // do a thing
};

La función mixin puede copiar las funciones desde el prototipo de la superclase para el prototipo de la subclase, la función mixin tiene que ser suministrada por el usuario. Un ejemplo de un mixin sería coomo la función  jQuery.extend.

Usando el argumento <propertiesObject> con Object.create

var o;

// crea un objeto con un prototipo como null
o = Object.create(null);


o = {};
// esto equivale a:
o = Object.create(Object.prototype);


// Ejemplo en donde creamos un objeto con un par de propiedades de ejemplo.
// (Note que el segundo parámetro mapea claves para los *descriptores de propiedad*.)
o = Object.create(Object.prototype, {
  // foo es un habitual "propiedad de valor"
  foo: { writable:true, configurable:true, value: "hello" },
  // bar es una propiedad getter-and-setter (de acceso)
  bar: {
    configurable: false,
    get: function() { return 10 },
    set: function(value) { console.log("Setting `o.bar` to", value) }
}});


function Constructor(){}
o = new Constructor();
// es equivalente a:
o = Object.create(Constructor.prototype);
// Por supuesto, si hay un código de inicialización en la
// función Constructor, el Object.create no puede reflejar esta.


// crear un nuevo objeto cuyo prototipo es un nuevo, objeto vacío
// y agregar una única propiedad 'p', con el valor 42
o = Object.create({}, { p: { value: 42 } })

// por defecto las propiedades NO SON editables, enumerables o configurables:
o.p = 24
o.p
// 42

o.q = 12
for (var prop in o) {
   console.log(prop)
}
// "q"

delete o.p
// false

// para especificar una propiedad en ES3

o2 = Object.create({}, { p: {
      value: 42,
      writable: true,
      enumerable: true,
      configurable: true }
});

Polyfill

Este polyfill cubre el caso de uso principal  el cual es la creación de un nuevo objeto para el prototipo que ha sido escogido pero no toma el segundo argumento en cuenta.

if (typeof Object.create != 'function') {
    (function () {
        var F = function () {};
        Object.create = function (o) {
            if (arguments.length > 1) { 
              throw Error('Second argument not supported');
            }
            if (o === null) { 
              throw Error('Cannot set a null [[Prototype]]');
            }
            if (typeof o != 'object') { 
              throw TypeError('Argument must be an object');
            }
            F.prototype = o;
            return new F();
        };
    })();
}

Especificaciones

Especificación Estatus Comentario
ECMAScript 5.1 (ECMA-262)
The definition of 'Object.create' in that specification.
Standard Definición inicial. Implementado en JavaScript 1.8.5
ECMAScript 6 (ECMA-262)
The definition of 'Object.create' in that specification.
Release Candidate  

Compatibilidad con navegadores

Característica  Chrome Firefox (Gecko) Internet Explorer Opera Safari
Soporte básico 5 4.0 (2) 9 11.60 5
Característica  Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Soporte básico (Yes) (Yes) 4.0 (2) (Yes) 11.50 (Yes)

Basado en la tabla compat de Kangax.

Ver también

Etiquetas y colaboradores del documento

 Colaboradores en esta página: jacoborus, teoli, Siro_Diaz, carlosmantilla
 Última actualización por: jacoborus,