在以下代码中,取自Helephant.com ,如果我将构造函数的原型(prototype) Cat.prototype = new Pet()
设置为另一个对象(Pet
)的原型(prototype),那么为什么它会修改其对象的构造函数 rufus.constructor
?
constructor
表示创建它的函数。父级如何在创建时进行修改?
//PET CONSTRUCTOR
function Pet(name, species, hello)
{ this.name = name;
this.species = species;
this.hello = hello; }
//CAT CONSTRUCTOR
function Cat(name, hello, breed, whiskerLength)
{ this.name = name;
this.hello = hello;
this.breed = breed;
this.whiskerLength = whiskerLength;}
//SETTING CAT's PROTOTYPE to A NEW PET OBJECT.
Cat.prototype = new Pet();
//CREATING A NEW CAT OBJECT
var rufus= new Cat("rufus", "miaow", "Maine Coon", 7);
//CALLING CAT OBJ's CONSTRUCTOR PROPERTY
rufus.constructor;
//OUTPUT
function Pet(name, species, hello)
{
this.name = name;
this.species = species;
this.hello = hello; }
这是设计上的小故障吗?任何人都可以解释这种行为。它带来什么好处?
最佳答案
当你输入 rufus.constructor
时,JavaScript 会检查 rufus
对象是否有这样的属性。它不在那里,因为你没有在那里创建它。然后向上遍历原型(prototype)链,在rufus.__proto__.__proto__
上找到指向Pet
函数的这个属性,输出这个函数。
这里有更详细的解释。当你声明一个函数时:
function Pet() {/* ..code.. */}
解释器根据您的声明创建新的函数对象。与函数一起,它的 prototype
属性被创建并填充。 prototype
的默认值是一个具有属性 constructor
的对象,它被设置为函数本身。在我们的例子中,Pet
:
Pet.prototype = { constructor: Pet}
此对象成为 new Pet()
的 .__proto__
并且可以通过 rufus.__proto__.__proto__
。这正是从中读取 rufus
访问constructor
属性的对象:
rufus.hasOwnProperty('constructor') // false;
Object.getPrototypeOf(rufus).hasOwnProperty('constructor') // false;
Object.getPrototypeOf(Object.getPrototypeOf(rufus)).hasOwnProperty('constructor') // true
这正是您会在 JavaScript 中的许多继承示例中看到在子对象上创建 constructor
属性的原因:
Cat.prototype = Object.create(Pet.prototype); // it's better to use this instead of new Pet()
Cat.prototype.constructor = Pet;
关于javascript - 如果更改构造函数的原型(prototype),为什么对象的构造函数属性会更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39997925/