Object.create指定原型创建对象,继承、原型链、纯字典对象三大经典场景

Object.create()作用一句话

创建一个新对象,并把它的原型([[Prototype]])指向指定对象

下面给你 3 个“面试 + 实战最经典”的例子,一看就懂 👇


⭐ 例子 1:最直观的原型继承(必会)

const animal = {
  eat() {
    console.log('eating');
  }
};

const dog = Object.create(animal);

dog.bark = function () {
  console.log('wang');
};

dog.eat();  // eating(来自原型)
dog.bark(); // wang(自身方法)

👉 dog 自己没有 eat,通过原型链从 animal 找到


⭐ 例子 2:经典“寄生组合继承”(面试高频)

function Parent(name) {
  this.name = name;
}

Parent.prototype.say = function () {
  console.log(this.name);
};

function Child(name, age) {
  Parent.call(this, name); // 继承属性
  this.age = age;
}

// 关键一行
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;

为什么要用 Object.create

  • ✅ 不执行 Parent 构造函数

  • ✅ 不共享实例属性

  • ✅ 原型链干净


⭐ 例子 3:创建“纯对象字典”(真实项目常用)

const map = Object.create(null);

map.a = 1;
map.b = 2;

console.log(map.toString);      // undefined
console.log('a' in map);        // true

适合:

  • key-value 存储

  • 防止 __proto__ 污染

  • {} 更安全


❌ 对比错误用法(常见坑)

const a = { x: 1 };
const b = Object.create(a);

a.x = 100;
console.log(b.x); // 100 ❌ 不是拷贝

👉 Object.create 不会复制对象,只是“指向”


🧠 对比一句话记忆

写法原型
{} Object.prototype
Object.create(obj) obj
Object.create(null) 无原型

📌 一句话总结

Object.create = 指定原型创建对象

继承、原型链、纯字典对象,三大经典场景

posted @ 2025-12-24 12:04  jerry-mengjie  阅读(3)  评论(0)    收藏  举报