当前位置:首页 > JavaScript

js prototype 实现

2026-04-06 06:04:29JavaScript

理解 JavaScript 的原型概念

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

使用 prototype 属性添加方法

函数在 JavaScript 中也是对象,每个函数都有一个 prototype 属性。通过 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 Animal(name) {
  this.name = name;
}

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

function Dog(name) {
  Animal.call(this, name);
}

Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

Dog.prototype.speak = function() {
  console.log(`${this.name} barks.`);
};

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

使用 Object.create 创建对象

Object.create 方法可以创建一个新对象,使用现有的对象作为新对象的原型。

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

const dog = Object.create(animal);
dog.name = 'Rex';
dog.speak = function() {
  console.log(`${this.name} barks.`);
};

dog.speak(); // 输出: Rex barks.

修改内置对象的原型

可以为内置对象(如 ArrayString)添加自定义方法,但需谨慎使用,以免与其他代码冲突。

js prototype 实现

Array.prototype.last = function() {
  return this[this.length - 1];
};

const arr = [1, 2, 3];
console.log(arr.last()); // 输出: 3

检查对象的原型

使用 Object.getPrototypeOf 可以获取对象的原型,instanceof 运算符可以检查对象是否在原型链上。

const arr = [];
console.log(Object.getPrototypeOf(arr) === Array.prototype); // true
console.log(arr instanceof Array); // true

避免直接修改 __proto__

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

const obj1 = { a: 1 };
const obj2 = { b: 2 };
Object.setPrototypeOf(obj2, obj1);
console.log(obj2.a); // 输出: 1

使用 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 dog = new Dog('Rex');
dog.speak(); // 输出: Rex barks.

标签: jsprototype
分享给朋友:

相关文章

js分组实现

js分组实现

分组实现方法 在JavaScript中,可以通过多种方式实现数组或对象的分组操作。以下是几种常见的方法: 使用Array.prototype.reduce() 通过reduce方法可以轻松实现数组分…

js 实现滚动

js 实现滚动

实现滚动的方法 使用 window.scrollTo() window.scrollTo() 方法可以滚动到文档中的特定位置。可以指定 x 和 y 坐标,或者使用平滑滚动的选项。 // 滚动到指定位…

js实现上传文件

js实现上传文件

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

js 实现日历

js 实现日历

实现日历的基本思路 日历的核心功能是展示日期,并允许用户进行日期选择或导航。JavaScript 可以动态生成日历的 HTML 结构,并处理用户交互逻辑。 基础日历结构 日历通常包含头部(显示月份和…

js实现复制功能实现

js实现复制功能实现

使用document.execCommand方法(传统方式,已逐渐被弃用) 传统方式通过document.execCommand('copy')实现复制功能,需先选中文本。以下是一个完整示例: fu…

js 实现mvc

js 实现mvc

MVC 模式简介 MVC(Model-View-Controller)是一种软件设计模式,将应用程序分为三个核心组件:模型(Model)处理数据和业务逻辑,视图(View)负责展示数据,控制器(Con…