【发布时间】:2020-07-29 04:50:05
【问题描述】:
此代码的目标是创建一个简单的 biz(业务)配置文件,使用继承方法 print 的构造函数和允许基于该方法呈现 biz 信息的构造函数,以及额外的东西 (size )。
预期的输出是“Hexis 的核心是技术”2。相反,我得到的是“未定义的核心是未定义”2。
在继承的print方法中,如何使bizOneHexis(PrintBizInfo的实例)的第一个参数作为this的参数传递?
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"
【问题讨论】:
标签: javascript binding this