JS继承的几种实现方式

1. 原型链继承

js 复制代码
function Parent() {
    this.name = 'parent';
}
Parent.prototype.getName = function() {
    return this.name;
};

function Child() {
    this.age = 18;
}
// 建立继承关系
Child.prototype = new Parent();
Child.prototype.constructor = Child;

const child = new Child();
console.log(child.getName()); // 'parent'

const child1 = new Child();
const child2 = new Child();
child1.colors.push('green');
console.log(child1.colors); // ['red', 'blue', 'green']
console.log(child2.colors); // ['red', 'blue', 'green']
缺点:
  • 引用类型的属性被所有实例共享
  • 创建子类实例时无法向父类构造函数传参`

2. 构造函数继承

js 复制代码
function Parent(name) {
    this.name = name;
    this.colors = ['red', 'blue'];
}

function Child(name) {
    // 调用父类构造函数
    Parent.call(this, name);
}

const child1 = new Child('child1');
const child2 = new Child('child2');
child1.colors.push('green');
console.log(child1.colors); // ['red', 'blue', 'green']
console.log(child2.colors); // ['red', 'blue']

缺点:

  • 方法都在构造函数中定义,每次创建实例都会创建一遍方法

3. 组合继承(原型链 + 构造函数)

js 复制代码
function Parent(name) {
    console.log('Parent', name)
    this.name = name;
    this.colors = ['red', 'blue'];
}
Parent.prototype.getName = function() {
    return this.name;
};

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

const child1 = new Child('child1', 18);
const child2 = new Child('child2', 20);

缺点:

  • 调用了两次父类构造函数

4. 原型式继承

js 复制代码
function createObj(o) {
    function F() {}
    F.prototype = o;
    return new F();
}

const parent = {
    name: 'parent',
    colors: ['red', 'blue']
};

const child1 = createObj(parent); //等于 Object.create(parent)
const child2 = createObj(parent);

缺点:

  • 引用类型的属性被所有实例共享

5. 寄生式继承

js 复制代码
function createAnother(original) {
    const clone = Object.create(original);
    clone.sayHi = function() {
        console.log('hi');
    };
    return clone;
}

const parent = {
    name: 'parent',
    colors: ['red', 'blue']
};

const child = createAnother(parent);

缺点:

  • 方法都在构造函数中定义,无法复用

6. 寄生组合式继承(最佳实践)

js 复制代码
function inheritPrototype(Child, Parent) {
    const prototype = Object.create(Parent.prototype);
    prototype.constructor = Child;
    Child.prototype = prototype;
}

function Parent(name) {
    this.name = name;
    this.colors = ['red', 'blue'];
}
Parent.prototype.getName = function() {
    return this.name;
};

function Child(name, age) {
    Parent.call(this, name);
    this.age = age;
}

inheritPrototype(Child, Parent);

Child.prototype.getAge = function() {
    return this.age;
};

const child = new Child('child', 18);

7. ES6 Class 继承

js 复制代码
class Parent {
    constructor(name) {
        this.name = name;
    }
    
    getName() {
        return this.name;
    }
}

class Child extends Parent {
    constructor(name, age) {
        super(name);
        this.age = age;
    }
    
    getAge() {
        return this.age;
    }
}

const child = new Child('child', 18);
补充 Object.create() 实现原理
1. 基本实现原理
js 复制代码
// 核心原理是:
// 1.  创建一个临时构造函数 F
// 2.  将传入的对象设置为该构造函数的原型
// 3.  返回这个构造函数的实例

function createObject(proto) {
    function F() {}
    F.prototype = proto;
    return new F();
}
2. 完整的 Object.create() 实现
js 复制代码
function objectCreate(proto, propertiesObject) {
    if (typeof proto !== 'object' && typeof proto !== 'function') {
        throw new TypeError('Object prototype may only be an Object or null');
    }

    // 创建一个临时构造函数
    function F() {}
    
    // 设置原型
    F.prototype = proto;
    
    // 创建新对象
    const obj = new F();
    
    // 如果提供了属性配置对象
    if (propertiesObject !== undefined) {
        Object.defineProperties(obj, propertiesObject);
    }
    
    // 如果原型是 null
    if (proto === null) {
        Object.setPrototypeOf(obj, null);
    }
    
    return obj;
}
3. 使用示例
js 复制代码
// 基本使用
const person = {
    name: 'Person',
    sayHello() {
        console.log(`Hello, I'm ${this.name}`);
    }
};

const john = Object.create(person, {
    name: {
        value: 'John',
        writable: true,
        enumerable: true,
        configurable: true
    },
    age: {
        value: 25,
        writable: false // 只读属性
    }
});

john.sayHello(); // 输出: "Hello, I'm John"
console.log(john.age); // 输出: 25
4. 特殊情况处理
js 复制代码
// 创建一个没有原型的对象
const noProto = Object.create(null);
console.log(Object.getPrototypeOf(noProto)); // null
console.log(noProto.__proto__); // undefined

// 使用现有对象作为原型
const parent = { x: 1 };
const child = Object.create(parent);
console.log(child.x); // 1
console.log(Object.getPrototypeOf(child) === parent); // true

Object.create() 的关键特点:

  1. 原型链继承
  • 可以直接指定对象的原型
  • 不调用构造函数,避免副作用
  • 可以创建一个没有原型的对象(传入 null)
  1. 属性描述符
  • 可以通过第二个参数精确定义属性
  • 支持配置属性的可写性、可枚举性和可配置性
  • 可以创建只读属性、访问器属性等
相关推荐
子兮曰1 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的
前端·后端·agent
子兮曰1 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议
前端·后端·ai编程
前端小万1 天前
写公众号赚了 3000 块后,我做了一款叫 "一键成稿" 的软件
前端·微信小程序
爱勇宝1 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"
前端·后端·chatglm (智谱)
三十而立洋1 天前
Cookie 详解:从产生到安全,一次讲透
前端·javascript
卡布鲁1 天前
把一个 Vite + Vue3 应用塞进 qiankun (React + Umi3) 主站:十个坑的复盘
前端·javascript·react.js
李少兄1 天前
JavaScript 隐式全局变量解析
javascript
汉堡大王95271 天前
Jev:不是聊天机器人, 而是一个智能 if 语句
前端·人工智能·后端
梦想很大很大1 天前
从运行事实到回归证据:Workrun 的 Telemetry 与 Evaluation 实践
前端·人工智能·后端
计算机魔术师1 天前
Meta Muse agent 接入 Shopify 的 Shop Pay 实现代理式购物
前端