freeCodeCamp/curriculum/challenges/chinese/02-javascript-algorithms-an.../object-oriented-programming/reset-an-inherited-construc...

2.3 KiB

id challengeType forumTopicId title
587d7db1367417b2b2512b86 1 301324 重置一个继承的构造函数属性

Description

当一个对象从另一个对象那里继承了其原型,那它也继承了父类的 constructor 属性。 请看下面的举例:
function Bird() { }
Bird.prototype = Object.create(Animal.prototype);
let duck = new Bird();
duck.constructor // function Animal(){...}

但是duck和其他所有Bird的实例都应该表明它们是由Bird创建的,而不是由Animal创建的。为此,你可以手动把Bird的 constructor 属性设置为Bird对象:

Bird.prototype.constructor = Bird;
duck.constructor // function Bird(){...}

Instructions

修改你的代码,使得duck.constructorbeagle.constructor返回各自的构造函数。

Tests

tests:
  - text: <code>Bird.prototype</code>应该是<code>Animal</code>的一个实例。
    testString: assert(Animal.prototype.isPrototypeOf(Bird.prototype));
  - text: <code>duck.constructor</code>应该返回<code>Bird</code>。
    testString: assert(duck.constructor === Bird);
  - text: <code>Dog.prototype</code>应该是<code>Animal</code>的一个实例。
    testString: assert(Animal.prototype.isPrototypeOf(Dog.prototype));
  - text: <code>beagle.constructor</code>应该返回<code>Dog</code>。
    testString: assert(beagle.constructor === Dog);

Challenge Seed

function Animal() { }
function Bird() { }
function Dog() { }

Bird.prototype = Object.create(Animal.prototype);
Dog.prototype = Object.create(Animal.prototype);

// Add your code below this line



let duck = new Bird();
let beagle = new Dog();

Solution

function Animal() { }
function Bird() { }
function Dog() { }
Bird.prototype = Object.create(Animal.prototype);
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Bird.prototype.constructor = Bird;
let duck = new Bird();
let beagle = new Dog();