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. 属性描述符
  • 可以通过第二个参数精确定义属性
  • 支持配置属性的可写性、可枚举性和可配置性
  • 可以创建只读属性、访问器属性等
相关推荐
sanx1812 分钟前
一站式电竞平台解决方案:数据、直播、源码,助力业务飞速启航
前端·数据库·apache·数据库开发·时序数据库
余防19 分钟前
存储型XSS,反射型xss
前端·安全·web安全·网络安全·xss
ObjectX前端实验室33 分钟前
从零到一:系统化掌握大模型应用开发【目录】
前端·llm·agent
guoyp212640 分钟前
前端实验(二)模板语法
前端·vue.js
葡萄城技术团队1 小时前
Excel 转在线协作难题破解:SpreadJS 纯前端表格控件的技术方案与实践
前端·excel
我的xiaodoujiao1 小时前
Windows系统Web UI自动化测试学习系列3--浏览器驱动下载使用
前端·windows·测试工具·ui
一只小风华~1 小时前
学习笔记:Vue Router 中的嵌套路由详解[特殊字符]概述
前端·javascript·vue.js
泻水置平地1 小时前
若依前后端分离版实现前端国际化步骤
前端
Villiam_AY1 小时前
从后端到react框架
前端·react.js·前端框架
CodeCraft Studio1 小时前
全球知名的Java Web开发平台Vaadin上线慧都网
java·开发语言·前端·vaadin·java开发框架·java全栈开发·java ui 框架