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. 属性描述符
  • 可以通过第二个参数精确定义属性
  • 支持配置属性的可写性、可枚举性和可配置性
  • 可以创建只读属性、访问器属性等
相关推荐
WEI_Gaot7 分钟前
3 使用工厂模式 和 构造函数 优化创建对象
前端·javascript
程序员小续11 分钟前
useContext 用法全解析:3 个实战案例带你上手!
前端·react.js·面试
1024小神12 分钟前
我使用github api同步文件到仓库后,立即触发工作流,这个时候工作流执行actions/checkout@v4,此时工作流中拿到的代码是最新的吗
前端·javascript
Factor安全28 分钟前
Chrome漏洞可窃取数据并获得未经授权的访问权限
前端·chrome·web安全·网络安全·安全威胁分析·安全性测试
齐尹秦40 分钟前
CSS 文本样式学习笔记
前端
程序员皮蛋鸽鸽43 分钟前
从零配置 Linux 与 Windows 互通的开发环境
前端·后端
kovli1 小时前
红宝书第十二讲:详解JavaScript中的工厂模式与原型模式等各种设计模式
前端·javascript
凯哥19701 小时前
Sciter.js 指南-核心概念:GUI应用程序项目结构、视图切换与组件化
前端
jinzunqinjiu1 小时前
学习react-native组件 1 Image加载图片的组件。
前端·react native
用户962337384501 小时前
CSS基础知识03
前端