Передача аргумента в метод, унаследованный экземпляром - PullRequest
0 голосов
/ 16 апреля 2020

Цель этого кода - создать простой бизнес-профиль, используя конструктор, который наследует метод print, и конструктор, который позволяет отображать информацию о бизнесе, основанную на этом методе, плюс что-то дополнительное (size ). Ожидаемый результат: «Ядро Hexis - технология» 2. Вместо этого я получаю «Ядро undefined не определено» 2.

Как сделать первый аргумент bizOneHexis (экземпляр PrintBizInfo) передать в качестве аргумента this в унаследованном методе print?

const bizDataBase = [
  {name: "Hexis", core: "tech"},
  {name: "Lexia", core: "consulting"}
  ]

function PrintBizCore (print){
  this.print = function (){
    //I want to pass bizDataBase[0] as the context of this.name etc.
    console.log(`The core of ${this.name} is ${this.core}` );
  }
  this.print();
}

function PrintBizInfo (print, size){
  PrintBizCore.call(this, print);
  this.size = 'Its size is ' + size;
}

let bizOneHexis = new PrintBizInfo (bizDataBase[0], 2); //-> The core of undefined is undefined
console.log(bizOneHexis.size); //-> "Its size is 2"

Я получил ожидаемый результат, изменив код следующим образом:

const bizDataBase = [
  {name: "Hexis", core: "tech"},
  {name: "Lexia", core: "consulting"}
  ]

function PrintBizCore (print){
  this.print = function (){
    console.log(`The core of ${bizDataBase[0].name} is ${bizDataBase[0].core}` );
  }
  this.print();
}

function PrintBizInfo (print, size){
  PrintBizCore.call(this, print);
  this.size = 'Its size is ' + size;
}

let bizOneHexis = new PrintBizInfo (bizDataBase[0], 2); //-> "The core of Hexis is tech"
console.log(bizOneHexis.size); //-> "Its size is 2"

1 Ответ

0 голосов
/ 17 апреля 2020

Я переделал код выше. Он не отвечает на некоторые мои вопросы, но решает, как получить желаемый результат (я думаю, что это немного интересно для программистов, работающих в проектах, подобных сервисам Bloomberg. В любом случае:

function PrintBizCore (print){
  this.print = function (){
    console.log(`The core of ${this.name} is ${this.core}` );
  }
  this.print();
}

const bizDataBase = [
  {name: "Hexis", core: "tech"}, {name: "Lexia", core: "consulting"}
  ];

function printer (obj){
  obj.forEach(function(brand){
    return PrintBizCore.call(brand)
  })
}

printer(bizDataBase);
//-> "The core of Hexis is tech"
//-> "The core of Lexia is consulting"
...