当前位置:首页 > 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语法是原型的语法糖,简化了原型继承的写法。

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 实现vue模板

js 实现vue模板

实现 Vue 模板的 JavaScript 方法 通过原生 JavaScript 可以实现类似 Vue 的模板渲染功能,主要包括数据绑定、指令处理和模板解析。以下是核心实现思路: 数据绑定与响应式…

js实现计算器

js实现计算器

实现基础计算器功能 使用JavaScript创建一个基础计算器需要处理数字输入、运算符逻辑和结果显示。以下是一个简单的实现示例: let currentInput = '0'; let previo…

js实现图片上传

js实现图片上传

图片上传的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API可以实现图片上传功能。HTML部分需要创建一个文件选择输入框和一个用于…

js 进度条的实现

js 进度条的实现

使用 HTML 和 CSS 创建基础进度条 HTML 结构可以简单使用一个 div 元素作为容器,内部嵌套另一个 div 表示进度: <div class="progress-contain…

js实现图片预览

js实现图片预览

使用FileReader API实现图片预览 通过FileReader对象读取用户选择的图片文件并显示预览: const input = document.getElementById('imag…

原生js实现轮播图

原生js实现轮播图

基本结构搭建 HTML部分需要包含轮播图容器、图片列表及导航按钮。结构示例如下: <div class="slider-container"> <div class="slid…