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

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

js实现拷贝

js实现拷贝

实现文本拷贝 使用 document.execCommand 方法(已废弃但兼容性较好): function copyText(text) { const textarea = document…

js实现dh

js实现dh

JavaScript 实现 DH(Diffie-Hellman)密钥交换 Diffie-Hellman(DH)密钥交换是一种安全协议,允许双方在不安全的通信信道上建立一个共享密钥。以下是如何在 Jav…

js实现密码

js实现密码

密码强度验证 使用正则表达式验证密码强度是一种常见方法。以下代码检查密码是否包含大小写字母、数字和特殊字符,且长度至少为8位: function checkPasswordStrength(pass…

js实现文字滚动

js实现文字滚动

实现文字滚动的几种方法 使用CSS动画实现滚动 通过CSS的@keyframes和transform属性可以实现平滑的文字滚动效果。 <style> .scroll-text { w…

js实现上传文件

js实现上传文件

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