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. 属性描述符
  • 可以通过第二个参数精确定义属性
  • 支持配置属性的可写性、可枚举性和可配置性
  • 可以创建只读属性、访问器属性等
相关推荐
web1508541593530 分钟前
Nginx 配置前端后端服务
运维·前端·nginx
AC-PEACE31 分钟前
JSX基础 —— 识别JS表达式
开发语言·javascript·react.js
BillKu32 分钟前
Element Plus中el-select选择器的下拉选项列表的样式设置
前端·javascript·vue.js
我家媳妇儿萌哒哒34 分钟前
el-table fixed滚动条被遮挡导致滚动条无法拖动
前端·javascript·vue.js
青春_strive1 小时前
HTML操作详解
前端·html
小华同学ai1 小时前
1.3K star!VisActor团队开源神器,3秒生成商业级图表,程序员直呼真香!
前端·github
Mrzheng1681 小时前
前端或者后端通常用到数组使用方式
前端
木亦Sam2 小时前
JavaScript 事件循环机制深度解析:为何你的代码执行顺序和预期不同?
前端·javascript
海绵波波1072 小时前
vue写一个登录页面
javascript·vue.js·ecmascript
郡nionio2 小时前
js的原型、原型链
javascript·面试