Object.create简介及Object.create(this)
Object.create() 是 JavaScript 中实现原型继承的核心方法。它的核心作用是:创建一个新对象,并使用现有的对象来提供新创建的对象的 __proto__(即 [[Prototype]])。下面我从基础语法、核心原理、与构造函数的区别、以及高级用法四个维度为你详细拆解。
1. 基础语法
javascript
Object.create(proto, [propertiesObject])
proto(必需):新对象的原型对象。如果传入null,则创建一个完全纯净、无原型的对象。propertiesObject(可选):一个对象,其属性会被添加到新对象上。注意:这里使用的是属性描述符(类似Object.defineProperties),而不是简单的键值对。
2. 核心原理与基础示例
javascript
const person = {
isHuman: false,
printIntroduction: function () {
console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
}
};
// 创建一个新对象,原型指向 person
const me = Object.create(person);
me.name = "Alice"; // "name" 是 me 自身的属性
me.isHuman = true; // 覆盖原型上的属性(属性遮蔽)
me.printIntroduction();
// 输出: "My name is Alice. Am I human? true"
// 验证原型链
console.log(Object.getPrototypeOf(me) === person); // true
console.log(me.hasOwnProperty('name')); // true (自身属性)
console.log(me.hasOwnProperty('isHuman')); // true (自身属性,覆盖了原型)
console.log(me.hasOwnProperty('printIntroduction')); // false (原型上的方法)
3. Object.create() vs new Constructor()
这是面试和实际开发中最常对比的点:
表格
| 特性 | Object.create(proto) |
new Constructor() |
|---|---|---|
| 执行逻辑 | 仅设置原型链,不执行任何初始化代码 | 创建对象 -> 设置原型 -> 执行构造函数 -> 返回对象 |
| 初始化 | 需手动赋值或使用第二个参数 | 在构造函数内部自动初始化 |
| 适用场景 | 纯原型继承、工厂模式、需要无初始化创建 | 传统的类/构造函数模式 |
javascript
function Animal(name) {
this.name = name;
console.log('Animal initialized!'); // 会被执行
}
const a = new Animal('Dog'); // 输出: Animal initialized!
const b = Object.create(Animal.prototype);
// 不会输出 "Animal initialized!"
// b.name 是 undefined,因为没有执行构造函数
根据Object.create(this)生成对应的示例,以理解Object.create和this两者结合的作用,如下所示:
// 修正:Object.create 是方法,需要调用时传原型,不能直接赋值
const obj = Object.create;
const mei = {
// 扩展生成新实例方法
extend: function () {
// 以当前mei对象为原型创建新对象
const ch = obj(this);
console.log("创建新子对象完成");
// 按顺序调用初始化、混入方法
ch.init();
ch.mixIn();
return ch; // 返回新对象供外部使用
},
// 初始化方法
init: function () {
console.log("执行 init 初始化函数");
// 示例:给实例挂载基础属性
this.name = "子实例";
this.age = 18;
},
// 属性混入方法(合并自定义配置)
mixIn: function (opts = {}) {
console.log("执行 mixIn 混入函数");
// 将传入配置合并到当前实例
Object.assign(this, opts);
}
};
// 测试使用
const child = mei.extend();
console.log("child实例:", child);
// 带参数调用mixIn演示(改造extend支持传参版)
const mei2 = {
extend: function (options) {
const ch = Object.create(this);
ch.init();
ch.mixIn(options);
return ch;
},
init() {
this.type = "组件";
},
mixIn(config) {
Object.assign(this, config);
}
};
// 传入自定义配置生成实例
const demo = mei2.extend({ id: 100, title: "测试组件" });
console.log("带配置实例:", demo);
代码执行输出
创建新子对象完成
执行 init 初始化函数
执行 mixIn 混入函数
child实例:{ name: '子实例', age: 18 }
执行 init 初始化函数
执行 mixIn 混入函数
带配置实例:{ type: '组件', id: 100, title: '测试组件' }

浙公网安备 33010602011771号