Object.create()是JavaScript中创建指定原型对象的方法,支持仅传原型对象或附加属性描述符;常用于手动实现原型继承、构造函数间继承及定义自有属性。

Object.create() 是 JavaScript 中用于创建新对象并指定其原型(prototype)的原生方法,常用于手动实现原型继承。
基本语法
最简用法:
Object.create(prototypeObj)完整形式(可选第二个参数定义属性):
Object.create(prototypeObj, propertiesObject)创建带原型的对象
让新对象直接继承某个对象的属性和方法:
const child = Object.create(parent);
console.log(child.sayHello()); // 'Hello'
console.log(child.__proto__ === parent); // true
配合构造函数模拟类继承
常见模式:子类型继承父类型的原型方法:
function Animal(name) { this.name = name; }Animal.prototype.speak = function() { return `${this.name} makes a sound.`; };
function Dog(name, breed) {
Animal.call(this, name); // 继承实例属性
this.breed = breed;
}
Dog.prototype = Object.create(Animal.prototype); // 关键:继承原型方法
Dog.prototype.constructor = Dog; // 修复 constructor 指向
const dog = new Dog('Buddy', 'Golden');
console.log(dog.speak()); // 'Buddy makes a sound.'
定义自有属性(第二个参数)
第二个参数是属性描述符对象,类似 Object.defineProperties() 的格式:
const proto = { x: 1 };const obj = Object.create(proto, {
y: { value: 2, writable: true, enumerable: true, configurable: true },
z: { get() { return this.y * 2; }, enumerable: true }
});
- value / get / set:指定数据属性或访问器属性
- writable / enumerable / configurable 控制属性行为
- 不传第二个参数时,新对象无自有属性,仅靠原型链访问
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











