本文介绍了如何正确使用Object.setPrototypeOf()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我已经加快了JavaScript的一些新功能的步伐,并一直在阅读有关Object.setPrototypeOf()的内容.我从 MDN 中查看了这段代码处理从常规对象继承.但是我对他们在这里如何使用Object.setPrototypeOf()感到困惑.我希望他们写

So I've been getting up to speed on some of the newer features of JavaScript and have been reading about Object.setPrototypeOf(). I ran across this bit of code from MDN which deals with inheriting from regular objects. But I'm confused at how they use Object.setPrototypeOf() here. I expected them to write

Object.setPrototypeOf(Dog, Animal) 

与下面的操作相反.他们为什么这样写?

as opposed to what the do below. Why do they write it this way?

var Animal = {
   speak() {
     console.log(this.name + ' makes a noise.');
   }
};

class Dog {
   constructor(name) {
   this.name = name;
  }
}

Object.setPrototypeOf(Dog.prototype, Animal);// If you do not do this you will get a TypeError when you invoke speak

var d = new Dog('Mitzie');
d.speak(); // Mitzie makes a noise.

推荐答案

调用Object.setPrototypeOf的原因是确保由Dog构造函数创建的任何对象都将在其原型链中获取Animal对象.设置构造函数本身的原型是错误的(不要与构造函数的prototype属性混淆,这确实是错误的称呼),因为构造函数在d的原型链中没有位置.

The reason for calling Object.setPrototypeOf is to make sure that any objects created by the Dog constructor will get the Animal object in their prototype chain. It would be wrong to set a prototype of the constructor itself (not to be confused with the constructor's prototype property which really is a misnomer), since the constructor has no place in d's prototype chain.

创建的Dog对象在其原型链中不会获取Dog,而是在Dog.prototype中. Dog只是 用于创建对象的工具,不应认为它本身已成为原型链的一部分.

A created Dog object does not get Dog in its prototype chain, but Dog.prototype. Dog is just the vehicle by which objects are created, it is not supposed itself to become part of the prototype chain.

可以Dog构造函数中执行此操作:

You could instead do this in the Dog constructor:

Object.setPrototypeOf(this, Animal)

这使原型链的长度缩短了一步,但缺点是现在d instanceof Dog将不再成立.它只会是一个Animal.这很可怜,它解释了为什么将原始Dog.prototype对象设置为Animal时将原始Dog.prototype对象保留为好,以便现在d既是Dog又是一个Animal.

That makes the length of the prototype chain one step shorter, but the downside is that now d instanceof Dog will no longer be true. It will only be an Animal. This is a pitty, and it explains why it is good to keep the original Dog.prototype object, while setting its prototype to Animal, so that now d is both a Dog and an Animal.

此处了解有关此主题的信息.我会针对该问答集宣传我自己的答案.

Read about this subject here. I would promote my own answer to that Q&A.

这篇关于如何正确使用Object.setPrototypeOf()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 07:35