【JS原型链,常见的修改原型对象的方法有哪些?】

原型链

  • 什么是原型链
  • 修改原型对象的方法
      • 1. 修改原型对象上的属性和方法
      • 2. 重写原型对象
      • 3. 使用Object.create创建新的原型对象
      • 4. 使用Object.setPrototypeOf修改原型链

什么是原型链

JavaScript中每个对象都有一个内部属性[[Prototype]]指向它的原型对象,原型对象也是一个对象,也有自己的原型,这样一直往上追溯形成了原型链。

原型链的作用是实现对象之间的继承和属性共享。当我们访问一个对象的属性时,如果这个对象本身没有这个属性,它就会沿着原型链向上查找,直到找到该属性或者到达原型链的末尾。

JavaScript中的每个函数都有一个prototype属性,它是一个对象,它的主要作用是存储实例对象共享的属性和方法。通过修改原型对象上的属性和方法,我们可以实现对实例对象的共享属性和方法进行修改。

修改原型对象的方法

下面是一些常见的修改原型对象的方法:

1. 修改原型对象上的属性和方法

function Person() {}
Person.prototype.name = 'Tom';
Person.prototype.sayName = function() {
  console.log('My name is', this.name);
}
const person1 = new Person();
const person2 = new Person();
person1.sayName(); // My name is Tom
person2.sayName(); // My name is Tom
Person.prototype.name = 'Jerry';
person1.sayName(); // My name is Jerry
person2.sayName(); // My name is Jerry

2. 重写原型对象

function Person() {}
Person.prototype = {
  name: 'Tom',
  sayName: function() {
    console.log('My name is', this.name);
  }
}
const person1 = new Person();
const person2 = new Person();
person1.sayName(); // My name is Tom
person2.sayName(); // My name is Tom
Person.prototype.name = 'Jerry';
person1.sayName(); // My name is Jerry
person2.sayName(); // My name is Jerry

3. 使用Object.create创建新的原型对象

function Person() {}
Person.prototype = Object.create({
  name: 'Tom',
  sayName: function() {
    console.log('My name is', this.name);
  }
});
const person1 = new Person();
const person2 = new Person();
person1.sayName(); // My name is Tom
person2.sayName(); // My name is Tom
Person.prototype.name = 'Jerry';
person1.sayName(); // My name is Jerry
person2.sayName(); // My name is Jerry

4. 使用Object.setPrototypeOf修改原型链

function Person() {}
Person.prototype.name = 'Tom';
const person1 = new Person();
const person2 = new Person();
person1.sayName = function() {
  console.log('My name is', this.name);
}
person1.sayName(); // My name is Tom
person2.sayName(); // TypeError: person2.sayName is not a function
Object.setPrototypeOf(person2, Person.prototype);
person2.sayName(); // My name is Tom

你可能感兴趣的:(面试常问问题,javascript,原型模式,开发语言)