14.在更改prototype时设置constructor属性

说明

手动将prototype设置为新对象有一个关键的副作用:它删除了constructor属性!那么之前挑战中的代码将会为duck打印以下内容:

注意

本人测试手动将prototype设置为新对象没有删除了constructor属性!即添加与否效果一样。

此文摘抄为W3Cschool编程学院编程入门实战训练

console.log(duck.constructor)
// 打印为'undefined'

要解决这个问题,只要在将prototype手动设置为新对象时,记得定义constructor属性:

Bird.prototype = {
  constructor: Bird, // 定义constructor属性
  numLegs: 2,
  eat: function() {
    console.log("nom nom nom");
  },
  describe: function() {
    console.log("My name is " + this.name);
  }
};


练习

Dogprototype上定义constructor属性。

  • Dog.prototype应设置constructor属性。

答案

方法 描述
this 当前执行代码的环境对象
constructor 属性 返回对创建此对象的数组函数的引用。
function Dog(name) {
this.name = name; 
}

// Modify the code below this line
Dog.prototype = {
constructor: Dog,
numLegs: 2, 
eat: function() {
console.log("nom nom nom"); 
}, 
describe: function() {
console.log("My name is " + this.name); 
}
};
发布了56 篇原创文章 · 获赞 1 · 访问量 815

猜你喜欢

转载自blog.csdn.net/weixin_44790207/article/details/105102790