[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/create [Back]  [Original]

Object.create() - JavaScript | MDN

Dieser Inhalt wurde automatisch aus dem Englischen bersetzt, und kann Fehler enthalten. Erfahre mehr ber dieses Experiment.

View in English Always switch to English

Object.create()

Baseline Weitgehend verfgbar

Diese Funktion ist gut etabliert und funktioniert auf vielen Gerten und in vielen Browserversionen. Sie ist seit Juli 2015 browserbergreifend verfgbar.

Die Object.create() statische Methode erstellt ein neues Objekt, indem sie ein vorhandenes Objekt als Prototyp des neu erstellten Objekts verwendet.

In diesem Artikel

Probieren Sie es aus

const person = {
  isHuman: false,
  printIntroduction() {
    console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
  },
};

const me = Object.create(person);

me.name = "Matthew"; // "name" is a property set on "me", but not on "person"
me.isHuman = true; // Inherited properties can be overwritten

me.printIntroduction();
// Expected output: "My name is Matthew. Am I human? true"

Syntax

js
Object.create(proto)
Object.create(proto, propertiesObject)

Parameter

proto

Das Objekt, das der Prototyp des neu erstellten Objekts sein sollte.

propertiesObject Optional

Falls angegeben und nicht undefined, ein Objekt, dessen aufzhlbare eigene Eigenschaften Eigenschaftsdeskriptoren angeben, die dem neu erstellten Objekt mit den entsprechenden Eigenschaftsnamen hinzugefgt werden sollen. Diese Eigenschaften entsprechen dem zweiten Argument von Object.defineProperties().

Rckgabewert

Ein neues Objekt mit dem angegebenen Prototyp-Objekt und den Eigenschaften.

Ausnahmen

TypeError

Wird ausgelst, wenn proto weder null noch ein Object ist.

Beispiele

Klassische Vererbung mit Object.create()

Nachfolgend ist ein Beispiel, wie Object.create() verwendet wird, um klassische Vererbung zu erreichen. Dies ist fr eine einzelne Vererbung, was JavaScript untersttzt.

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

// superclass method
Shape.prototype.move = function (x, y) {
  this.x += x;
  this.y += y;
  console.info("Shape moved.");
};

// Rectangle - subclass
function Rectangle() {
  Shape.call(this); // call super constructor.
}

// subclass extends superclass
Rectangle.prototype = Object.create(Shape.prototype, {
  // If you don't set Rectangle.prototype.constructor to Rectangle,
  // it will take the prototype.constructor of Shape (parent).
  // To avoid that, we set the prototype.constructor to Rectangle (child).
  constructor: {
    value: Rectangle,
    enumerable: false,
    writable: true,
    configurable: true,
  },
});

const rect = new Rectangle();

console.log("Is rect an instance of Rectangle?", rect instanceof Rectangle); // true
console.log("Is rect an instance of Shape?", rect instanceof Shape); // true
rect.move(1, 1); // Logs 'Shape moved.'

Beachten Sie, dass es Vorsichtsmanahmen gibt, auf die Sie bei der Verwendung von create() achten mssen, wie z.B. das erneute Hinzufgen der constructor-Eigenschaft, um die korrekten Semantiken sicherzustellen. Obwohl Object.create() als leistungsstrker als das Mutieren des Prototyps mit Object.setPrototypeOf() betrachtet wird, ist der Unterschied tatschlich vernachlssigbar, wenn noch keine Instanzen erstellt wurden und auf Eigenschaften noch nicht optimiert zugegriffen wurde. Im modernen Code sollte in jedem Fall die class-Syntax bevorzugt werden.

Verwenden des parameters propertiesObject mit Object.create()

Object.create() ermglicht eine fein abgestimmte Kontrolle ber den Objekt-Erstellungsprozess. Die Objektinitialisierer-Syntax ist tatschlich ein Syntaxzucker von Object.create(). Mit Object.create() knnen wir Objekte mit einem bestimmten Prototyp und auch mit einigen Eigenschaften erstellen. Beachten Sie, dass der zweite Parameter Schlssel auf Eigenschaftsdeskriptoren abbildet das bedeutet, dass Sie die Aufzhlbarkeit, Konfigurierbarkeit usw. jeder Eigenschaft ebenfalls steuern knnen, was in Objektinitialisierern nicht mglich ist.

js
o = {};
// Is equivalent to:
o = Object.create(Object.prototype);

o = Object.create(Object.prototype, {
  // foo is a regular data property
  foo: {
    writable: true,
    configurable: true,
    value: "hello",
  },
  // bar is an accessor property
  bar: {
    configurable: false,
    get() {
      return 10;
    },
    set(value) {
      console.log("Setting `o.bar` to", value);
    },
  },
});

// Create a new object whose prototype is a new, empty
// object and add a single property 'p', with value 42.
o = Object.create({}, { p: { value: 42 } });

Mit Object.create() knnen wir ein Objekt mit null als Prototyp erstellen. Die entsprechende Syntax in Objektinitialisierern wre der __proto__-Schlssel.

js
o = Object.create(null);
// Is equivalent to:
o = { __proto__: null };

Standardmig sind Eigenschaften nicht schreibbar, aufzhlbar oder konfigurierbar.

js
o.p = 24; // throws in strict mode
o.p; // 42

o.q = 12;
for (const prop in o) {
  console.log(prop);
}
// 'q'

delete o.p;
// false; throws in strict mode

Um eine Eigenschaft mit denselben Attributen wie in einem Initialisierer anzugeben, muss writable, enumerable und configurable explizit angegeben werden.

js
o2 = Object.create(
  {},
  {
    p: {
      value: 42,
      writable: true,
      enumerable: true,
      configurable: true,
    },
  },
);
// This is not equivalent to:
// o2 = Object.create({ p: 42 })
// which will create an object with prototype { p: 42 }

Sie knnen Object.create() verwenden, um das Verhalten des new-Operators nachzuahmen.

js
function Constructor() {}
o = new Constructor();
// Is equivalent to:
o = Object.create(Constructor.prototype);

Natrlich kann, wenn es tatschlichen Initialisierungscode in der Constructor-Funktion gibt, die Object.create()-Methode diesen nicht wiedergeben.

Spezifikationen

Spezifikation
ECMAScript 2027 LanguageSpecification
# sec-object.create

Browser-Kompatibilitt

Siehe auch


Web Proxy Viewer  |  New URL  |  Original Page