说明
手动将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);
}
};
练习
在Dog
的prototype
上定义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);
}
};