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); 
}
};

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值