当前位置:首页 > JavaScript

js prototype 实现

2026-02-01 13:16:30JavaScript

理解 JavaScript 原型链

JavaScript 是一种基于原型的语言,每个对象都有一个原型对象,对象从原型继承属性和方法。原型链是 JavaScript 实现继承的核心机制。

创建对象并使用原型

通过构造函数创建对象时,新对象的原型会指向构造函数的 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

原型链继承

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

js 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.setPrototypeOf

ES6 提供了 Object.setPrototypeOf 方法直接设置对象的原型:

const animal = {
  eat() {
    console.log(`${this.name} eats`);
  }
};

const dog = {
  name: 'Rex',
  bark() {
    console.log(`${this.name} barks`);
  }
};

Object.setPrototypeOf(dog, animal);
dog.eat(); // 输出: Rex eats
dog.bark(); // 输出: Rex barks

原型链的终点

所有对象的原型链最终指向 Object.prototype,而 Object.prototype 的原型是 null

js prototype 实现

console.log(Object.getPrototypeOf(Object.prototype)); // 输出: null

检查原型关系

使用 instanceof 运算符可以检查对象是否在原型链上:

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

避免直接修改内置原型

虽然可以修改内置对象的原型(如 Array.prototype),但这通常是不推荐的,因为它可能导致不可预测的行为:

Array.prototype.customMethod = function() {
  console.log('Custom array method');
};

const arr = [1, 2, 3];
arr.customMethod(); // 输出: Custom array method

性能考虑

过长的原型链会影响性能,因为查找属性时需要遍历整个链。尽量保持原型链简洁。

标签: jsprototype
分享给朋友:

相关文章

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 使用JavaScript实现拖拽功能需要监听鼠标事件,包括mousedown、mousemove和mouseup。以下是实现的基本逻辑: const draggableEleme…

js实现图片上传

js实现图片上传

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

js如何实现继承

js如何实现继承

原型链继承 通过将子类的原型指向父类的实例实现继承。子类实例能够访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Parent…

js手势实现

js手势实现

手势识别实现方法 在JavaScript中实现手势识别通常涉及监听触摸事件(touchstart、touchmove、touchend)或鼠标事件(mousedown、mousemove、mouseu…

js实现图

js实现图

JavaScript 实现图的常用方法 在 JavaScript 中,图(Graph)可以通过多种方式实现,常见的包括邻接表(Adjacency List)和邻接矩阵(Adjacency Matrix…

js实现vue路由

js实现vue路由

Vue 路由的基本实现 在 Vue.js 中实现路由功能通常使用 Vue Router 库。Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。 安装 Vue R…