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

Object.create() - JavaScript | MDN

MDN Web Docs

View in English Always switch to English

Object.create()

Baseline

20157

Object.create()

const person = {
  isHuman: false,
  printIntroduction() {
    console.log(` ${this.name}  ${this.isHuman}`);
  },
};

const me = Object.create(person);

me.name = "Matthew"; // "name"  "me"  "person" 
me.isHuman = true; // 

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

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

proto

propertiesObject

undefined Object.defineProperties() 2

TypeError

proto null Object

Object.create()

Object.create() JavaScript

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

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

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

// 
Rectangle.prototype = Object.create(Shape.prototype, {
  // Rectangle.prototype.constructor  Rectangle 
  // Shape ()  prototype.constructor 
  //  prototype.constructor  Rectangle () 
  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); // 'Shape moved.' 

create() constructor Object.create() Object.setPrototypeOf() JavaScript class

Object.create() propertiesObject

Object.create() Object.create() Object.create() 2

js
o = {};
// 
o = Object.create(Object.prototype);

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

// 
//  'p'  42 
o = Object.create({}, { p: { value: 42 } });

Object.create() null __proto__

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

js
o.p = 24; // 
o.p; // 42

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

delete o.p;
// false; 

writableenumerableconfigurable

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

Object.create() new

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

constructor Object.create()

ECMAScript 2027 LanguageSpecification
# sec-object.create


Web Proxy Viewer  |  New URL  |  Original Page