object.create()更高效,因它直接以指定对象为原型创建新对象,不执行父类构造函数,避免不必要的初始化开销和副作用;标准三行写法语义清晰、无冗余、兼容es5+。

用 Object.create() 替换 new Parent(),配合手动修正 constructor,就是最少且高效的原型继承写法。
为什么 Object.create() 更高效?
它直接以指定对象为原型创建新对象,不执行父类构造函数,避免了不必要的初始化开销和副作用(比如重复赋值、副作用逻辑触发等)。
-
Child.prototype = new Parent():会真正调用一次Parent构造函数,哪怕你只想要它的原型方法 -
Child.prototype = Object.create(Parent.prototype):跳过构造函数,仅建立原型链连接
标准三行写法(推荐)
只需三行,语义清晰、无冗余、兼容性好(ES5+):
PigX UI Pro 前端开发指南 - Vue 3 + TypeScript + Element Plus。当用户提到 PigX UI、PigX 前端、lgb-mgui 项目、Vue 3 企业级后台开发、Element Plus 后台开发时使用此技能。
Child.prototype = Object.create(Parent.prototype);-
Child.prototype.constructor = Child;(修复 constructor 指向) -
Child.__proto__ = Parent;(可选,仅当需静态方法继承时加)
完整最小示例
对比传统写法,更轻量、更安全:
function Parent() { this.type = 'parent'; }
Parent.prototype.say = function() { console.log('hi'); };
function Child() {}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
const c = new Child();
c.say(); // hi
console.log(c instanceof Parent); // true
注意两个关键点
缺一不可,否则会出问题:
- 不设
Object.create(Parent.prototype)→ 子类无法访问父类原型方法 - 不修
constructor→new Child()实例的constructor会指向Parent,影响类型判断和实例检查










