返回

巧妙驾驭原型对象,进阶JS编程的必备之钥

前端

原型链的奥秘

在JS王国中,原型链犹如一座错综复杂的迷宫,将各个对象紧密相连。每个对象都拥有一个隐藏的[[Prototype]]属性,它指向对象的原型。

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

Person.prototype.sayHello = function() {
  console.log(`Hello, my name is ${this.name}`);
};

const person1 = new Person('Alice');
const person2 = new Person('Bob');

console.log(person1.__proto__ === Person.prototype); // true
console.log(person2.__proto__ === Person.prototype); // true

从代码中可以看出,person1和person2都是Person函数的实例,它们都继承了Person.prototype中的sayHello方法。当我们调用person1.sayHello()时,实际上是通过[[Prototype]]属性访问Person.prototype中的sayHello方法。

原型对象与[[Prototype]]属性的关系

[[Prototype]]属性是对象的原型,它存储着对象的共有属性和方法。每个对象都有一个[[Prototype]]属性,指向其原型。原型对象也是一个对象,它也有自己的[[Prototype]]属性,依次类推,直到原型链的顶端——Object.prototype。

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

Person.prototype.sayHello = function() {
  console.log(`Hello, my name is ${this.name}`);
};

const person1 = new Person('Alice');

console.log(person1.__proto__ === Person.prototype); // true
console.log(Person.prototype.__proto__ === Object.prototype); // true

在上面的代码中,person1的[[Prototype]]属性指向Person.prototype,Person.prototype的[[Prototype]]属性指向Object.prototype。因此,person1可以访问Person.prototype中的sayHello方法,也可以访问Object.prototype中的toString方法。

巧妙运用原型对象

掌握了原型对象的概念,我们可以巧妙地运用它来实现许多有趣的功能。

1. 扩展对象

我们可以通过修改原型对象来扩展对象的功能。例如,我们可以为Person原型对象添加一个getAge方法,用于获取对象的年龄。

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

Person.prototype.getAge = function() {
  return this.age;
};

const person1 = new Person('Alice', 20);

console.log(person1.getAge()); // 20

2. 共享属性和方法

原型对象还可以帮助我们共享属性和方法。例如,我们可以为Person原型对象添加一个sayHello方法,用于向对象打招呼。

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

Person.prototype.sayHello = function() {
  console.log(`Hello, my name is ${this.name}`);
};

const person1 = new Person('Alice');
const person2 = new Person('Bob');

person1.sayHello(); // Hello, my name is Alice
person2.sayHello(); // Hello, my name is Bob

3. 实现继承

原型对象还可以帮助我们实现继承。例如,我们可以创建一个Student类,它继承自Person类。

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

Person.prototype.sayHello = function() {
  console.log(`Hello, my name is ${this.name}`);
};

function Student(name, major) {
  Person.call(this, name);
  this.major = major;
}

Student.prototype = Object.create(Person.prototype);

Student.prototype.constructor = Student;

Student.prototype.study = function() {
  console.log(`I am studying ${this.major}`);
};

const student1 = new Student('Alice', 'Computer Science');

student1.sayHello(); // Hello, my name is Alice
student1.study(); // I am studying Computer Science

在上面的代码中,Student类继承了Person类的属性和方法。student1可以访问Person.prototype中的sayHello方法,也可以访问Student.prototype中的study方法。

结语

原型对象是JS编程中非常重要的概念,掌握了原型对象的概念,我们可以巧妙地运用它来实现许多有趣的功能。我希望这篇文章能够帮助您更好地理解原型对象。