Object.create()的核心作用是直接创建以指定对象为原型的新对象。它接收必填的原型对象和可选的属性描述符,支持创建无原型对象、手动设置constructor及嵌套构建多级原型链。

Object.create() 的核心作用就是直接创建一个新对象,并让这个新对象的 [[Prototype]] 指向你指定的对象——无需定义构造函数,也不涉及 new 关键字。它是最简洁、最直观实现原型关联的方式。
明确指定原型对象
传入一个对象作为参数,Object.create 就会返回一个以该对象为原型的新对象:
- 第一个参数是必填的,表示新对象的原型(即
__proto__指向的目标) - 第二个参数可选,用于定义新对象自身的属性描述符(如
writable、enumerable等)
例如:
const animal = {
eat() { return 'eating...' }
};
const dog = Object.create(animal);
console.log(dog.eat()); // 'eating...'
console.log(Object.getPrototypeOf(dog) === animal); // true
避免构造函数的干扰
传统方式中,我们常通过构造函数 + prototype 属性建立原型链,但这隐含了对 constructor 和 instanceof 的预期,而有时你只需要纯粹的委托关系。
- 用
Object.create(null)可创建“无原型”对象,彻底避开Object.prototype上的方法(如toString) - 若仅需数据容器或配置对象,不希望被误判为某个类的实例,就不要引入构造函数
比如创建一个纯字典对象:
const config = Object.create(null); config.apiBase = '/v1'; config.timeout = 5000; // config.toString // undefined —— 不继承自 Object.prototype
手动设置 constructor(按需)
使用 Object.create() 创建的对象,默认没有 constructor 属性,除非原型上显式定义了它。这通常不是问题,但如果你依赖 obj.constructor 做类型识别,可以手动补上:
- 在原型对象上添加
constructor属性,指向语义上的“类型” - 注意:这仅是约定,不影响实际行为,
instanceof依然不成立(因为没用 new)
示例:
const vehicle = {
constructor: Vehicle,
start() { return 'engine running'; }
};
const car = Object.create(vehicle);
console.log(car.constructor === Vehicle); // true(仅因我们写了)
console.log(car instanceof Vehicle); // false(没经过 new Vehicle())
组合多个原型层级(间接方式)
Object.create() 本身只支持单层原型指定,但你可以嵌套调用,构建多级原型链:
- 先用
Object.create(A)得到 B - 再用
Object.create(B)得到 C,此时 C → B → A
例如:
const living = { breathe() { return 'inhale/exhale'; } };
const mammal = Object.create(living);
mammal.warmBlooded = true;
const human = Object.create(mammal);
human.speak = function() { return 'hello'; };
console.log(human.speak()); // 'hello'
console.log(human.warmBlooded); // true
console.log(human.breathe()); // 'inhale/exhale'










