当前位置:首页 > JavaScript

js prototype 实现

2026-03-14 12:07:41JavaScript

原型(Prototype)的概念

在JavaScript中,每个函数都有一个特殊的属性叫做prototype。这个属性指向一个对象,该对象包含了可以由特定类型的所有实例共享的属性和方法。原型的主要作用是实现继承和共享属性。

原型的基本实现

定义一个构造函数,并通过原型添加方法:

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

Person.prototype.greet = function() {
  console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
};

const person1 = new Person('Alice', 25);
person1.greet(); // 输出: Hello, my name is Alice and I am 25 years old.

原型链继承

通过原型链实现继承,子类的原型指向父类的实例:

js prototype 实现

function Student(name, age, grade) {
  Person.call(this, name, age); // 调用父类构造函数
  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', 16, 10);
student1.greet(); // 输出: Hello, my name is Bob and I am 16 years old.
student1.study(); // 输出: Bob is studying in grade 10.

原型方法的重写

子类可以重写父类的方法:

Student.prototype.greet = function() {
  console.log(`Hi, I'm ${this.name}, a student in grade ${this.grade}.`);
};

student1.greet(); // 输出: Hi, I'm Bob, a student in grade 10.

静态方法与实例方法

静态方法是直接定义在构造函数上的方法,实例方法是定义在原型上的方法:

js prototype 实现

Person.staticMethod = function() {
  console.log('This is a static method.');
};

Person.staticMethod(); // 输出: This is a static method.

原型链的查找机制

当访问一个对象的属性或方法时,JavaScript会先在对象自身查找,如果没有找到,会沿着原型链向上查找,直到找到或到达原型链的顶端(null)。

console.log(student1.hasOwnProperty('name')); // true
console.log(student1.hasOwnProperty('greet')); // false

使用Object.getPrototypeOf__proto__

获取对象的原型:

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

原型与性能

共享方法通过原型实现可以减少内存占用,因为所有实例共享同一个方法,而不是每个实例都创建一份方法的副本。

标签: jsprototype
分享给朋友:

相关文章

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 通过监听鼠标事件(mousedown、mousemove、mouseup)实现拖拽功能。以下是核心代码逻辑: const draggableElement = document.…

js实现日历

js实现日历

实现日历的基本思路 使用JavaScript实现日历的核心是动态生成日期表格,并处理月份切换逻辑。需要计算当前月的天数、起始星期几,并动态渲染到页面上。 获取当前日期信息 通过Date对象获取当前年…

jquery.js

jquery.js

jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画设计和 Ajax 交互等操作。以下是关于 jQuery.js 的核心信息和使用方法: 获取 jQ…

js实现预览

js实现预览

文件上传预览实现 使用JavaScript实现文件上传预览功能,可以通过FileReader对象读取文件内容并显示预览。以下代码支持图片、文本和PDF文件的预览: // HTML部分需要包含…

js实现游标

js实现游标

使用JavaScript实现游标 在JavaScript中,可以通过操作DOM元素的cursor样式属性来实现自定义游标效果。以下是几种常见的实现方法: 修改默认鼠标指针样式 通过CSS的curso…

js实现 功能

js实现 功能

在 JavaScript 中实现功能通常涉及多个关键步骤,具体取决于功能需求。以下是常见功能的实现方法和示例: 基本功能实现 使用函数封装逻辑是最直接的方式。例如,实现一个计算两数之和的函数: f…