该代码的目标是使用继承方法print
的构造函数和允许呈现Biz信息的构造函数,基于该方法,再加上一些额外的内容[size
),创建一个简单的biz(业务)配置文件。 。预期的输出是“ Hexis的核心是技术”2。相反,我得到的是“ undefined的核心是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"
我重构了上面的代码。它没有回答我的一些问题,但是解决了如何获得所需的输出(我认为这对于从事类似于彭博社服务项目的程序员来说有点有趣。无论如何:
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"