Доступ к унаследованной функции от ребенка - PullRequest
0 голосов
/ 13 июня 2018

Первый код:

function Animal() {}
Animal.prototype.eat = function() {
  console.log("nom nom nom");
};

function Dog() {}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype = {
  constructor: Dog,
  bark: function() {
    console.log("Woof!");
  }
};
let beagle = new Dog();
console.clear();
beagle.eat(); // Should print "nom nom nom" but displays a error that eat 
//is not a function.
beagle.bark();

Второй код:

function Animal() {}
Animal.prototype.eat = function() {
  console.log("nom nom nom");
};

function Dog() {}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function() {
  console.log("Woof!");
}
let beagle = new Dog();
console.clear();
beagle.eat(); // Prints "nom nom nom"
beagle.bark(); // Prints "Woof!"

Что не так с первым фрагментом кода, который beagle.eat() не показывает правильный вывод.

1 Ответ

0 голосов
/ 13 июня 2018

Сначала вы присваиваете прототип Dog как Object.create(Animal.prototype);, но затем на следующей строке вы полностью переназначаете прототип Dog на что-то другое, поэтому цепочка наследования больше не будетсуществует.Настраивая свой первый код, вы можете просто присвоить Dog.prototype только один раз и использовать Object.assign вместе с Object.create:

function Animal() {}
Animal.prototype.eat = function() {
  console.log("nom nom nom");
};

function Dog() {}
Dog.prototype = Object.assign(
  Object.create(Animal.prototype),
  {
    constructor: Dog,
    bark: function() {
      console.log("Woof!");
    }
  }
);
let beagle = new Dog();
beagle.eat();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...