当前位置:首页 > 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实现复制

使用document.execCommand方法 在较旧的浏览器中,可以使用document.execCommand('copy')实现复制功能。创建一个临时的textarea或input元素,将需要…

js jquery

js jquery

jQuery 简介 jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画设计和 Ajax 交互。它兼容多种浏览器,提供易于使用的 API,使开发者能够…

js实现百叶窗

js实现百叶窗

使用CSS和JavaScript实现百叶窗效果 通过CSS动画和JavaScript事件监听可以实现百叶窗效果。核心思路是将内容区域分割为多个条状元素,通过控制它们的展开/折叠状态来模拟百叶窗。…

js实现按钮点击

js实现按钮点击

实现按钮点击的JavaScript方法 HTML按钮元素 在HTML中创建按钮元素,为其添加id或class以便JavaScript选择: <button id="myButton">点…

js实现定位

js实现定位

使用Geolocation API获取当前位置 在JavaScript中,可以通过浏览器内置的Geolocation API获取用户的地理位置信息。该API需要用户授权才能访问位置数据。 if (n…

实现继承js

实现继承js

实现继承的方式 在JavaScript中,实现继承可以通过多种方式完成,每种方式都有其优缺点。以下是几种常见的实现继承的方法: 原型链继承 原型链继承是最基本的继承方式,通过将子类的原型指向父类的实…