当前位置:首页 > JavaScript

js原型实现

2026-02-01 17:44:06JavaScript

理解原型的基本概念

在JavaScript中,每个对象都有一个原型(prototype),原型本身也是一个对象。对象从原型继承属性和方法。原型链是JavaScript实现继承的机制。

使用构造函数创建对象

构造函数用于创建对象实例。通过new关键字调用构造函数时,会创建一个新对象,并将该对象的原型指向构造函数的prototype属性。

function Person(name) {
    this.name = name;
}

Person.prototype.greet = function() {
    console.log(`Hello, my name is ${this.name}`);
};

const person1 = new Person('Alice');
person1.greet(); // 输出: Hello, my name is Alice

原型链继承

通过原型链,子构造函数可以继承父构造函数的属性和方法。子构造函数的prototype指向父构造函数的实例。

function Student(name, grade) {
    Person.call(this, name);
    this.grade = grade;
}

Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;

Student.prototype.study = function() {
    console.log(`${this.name} is studying in grade ${this.grade}`);
};

const student1 = new Student('Bob', 5);
student1.greet(); // 输出: Hello, my name is Bob
student1.study(); // 输出: Bob is studying in grade 5

使用Object.create创建对象

Object.create方法可以创建一个新对象,并指定其原型。

const animal = {
    speak() {
        console.log(`${this.name} makes a noise.`);
    }
};

const dog = Object.create(animal);
dog.name = 'Rex';
dog.speak(); // 输出: Rex makes a noise.

修改原型

原型可以在运行时动态修改,所有实例都会受到影响。

function Car(model) {
    this.model = model;
}

const car1 = new Car('Tesla');
Car.prototype.drive = function() {
    console.log(`${this.model} is driving.`);
};

car1.drive(); // 输出: Tesla is driving.

检查原型关系

使用instanceofObject.getPrototypeOf可以检查对象的原型关系。

console.log(student1 instanceof Student); // true
console.log(student1 instanceof Person); // true
console.log(Object.getPrototypeOf(student1) === Student.prototype); // true

避免直接修改__proto__

虽然__proto__属性可以访问对象的原型,但直接修改它不推荐使用。应使用Object.createObject.setPrototypeOf

const cat = {
    purr() {
        console.log('Purring...');
    }
};

const kitten = Object.create(cat);
kitten.purr(); // 输出: Purring...

使用ES6的class语法

ES6的class语法是原型的语法糖,简化了原型继承的写法。

js原型实现

class Animal {
    constructor(name) {
        this.name = name;
    }

    speak() {
        console.log(`${this.name} makes a noise.`);
    }
}

class Dog extends Animal {
    speak() {
        console.log(`${this.name} barks.`);
    }
}

const d = new Dog('Rex');
d.speak(); // 输出: Rex barks.

标签: 原型js
分享给朋友:

相关文章

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 实现页面跳转,这是最常用的方法。 window.location.href = 'https://…

js实现选项卡

js实现选项卡

实现选项卡的基本思路 选项卡通常由一组标签和对应的内容面板组成。点击标签时,显示对应的内容面板,隐藏其他面板。实现这一效果需要结合HTML结构、CSS样式和JavaScript交互逻辑。 HTML结…

js实现防洪

js实现防洪

防抖(Debounce)实现 防抖的核心思想是在事件触发后延迟执行回调函数,若在延迟时间内再次触发事件,则重新计时。适用于输入框搜索、窗口调整等场景。 function debounce(f…

js实现搜索

js实现搜索

实现搜索功能的方法 在JavaScript中实现搜索功能可以通过多种方式完成,以下是几种常见的实现方法。 使用数组的filter方法 通过数组的filter方法可以筛选出符合条件的数据项。假设有一个…

js实现上传文件

js实现上传文件

文件上传的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API可以实现文件上传功能。 <input type="file"…

js实现原理

js实现原理

JavaScript 实现原理 JavaScript 是一种解释型语言,其实现原理涉及多个核心组件和运行机制,包括引擎、运行时环境、事件循环等。 引擎与解释执行 现代 JavaScript 引擎(如…