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

Object.setPrototypeOf() - JavaScript | MDN

MDN Web Docs

View in English Always switch to English

Object.setPrototypeOf()

Baseline

20159

Object.setPrototypeOf() [[Prototype]] null

: [[Prototype]] JavaScript JavaScript Object.setPrototypeOf(...) [[Prototype]] JavaScript engine fundamentals: optimizing prototypes

() [[Prototype]] Object.create() [[Prototype]]

const obj = {};
const parent = { foo: "bar" };

console.log(obj.foo);
// : undefined

Object.setPrototypeOf(obj, parent);

console.log(obj.foo);
// : "bar"

js
Object.setPrototypeOf(obj, prototype)

obj

prototype

null

TypeError

  • obj undefined null
  • obj Object.prototype window obj
  • prototype null

Object.setPrototypeOf() Object.prototype.__proto__

obj obj prototype obj obj TypeError obj

Object.prototype null window location 2

js
Object.isExtensible(Object.prototype); // true
Object.setPrototypeOf(Object.prototype, {}); // TypeError:  '#<Object>' 
Object.setPrototypeOf(Object.prototype, null); //  `Object.prototype`  `null` 

Object.setPrototypeOf()

JS

js
class Human {}
class SuperHero extends Human {}

const superMan = new SuperHero();

class

js
function Human(name, level) {
  this.name = name;
  this.level = level;
}

function SuperHero(name, level) {
  Human.call(this, name, level);
}

Object.setPrototypeOf(SuperHero.prototype, Human.prototype);

// `SuperHero.prototype`  `[[Prototype]]`  `Human.prototype` 
// 

Human.prototype.speak = function () {
  return `${this.name} says hello.`;
};

SuperHero.prototype.fly = function () {
  return `${this.name} is flying.`;
};

const superMan = new SuperHero("Clark Kent", 1);

console.log(superMan.fly());
console.log(superMan.speak());

prototype

prototype Object.create() create() constructor

SuperHero extends setPrototypeOf() Human

: extends setPrototypeOf()

js
class Human {}
class SuperHero {}

// 
Object.setPrototypeOf(SuperHero.prototype, Human.prototype);

// 
Object.setPrototypeOf(SuperHero, Human);

const superMan = new SuperHero();

extends ES-6 subclassing

ECMAScript 2027 LanguageSpecification
# sec-object.setprototypeof


Web Proxy Viewer  |  New URL  |  Original Page