【问题标题】:Passing an argument to a method inherited by an instance将参数传递给实例继承的方法
【发布时间】: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


    【解决方案1】:

    我重构了上面的代码。它没有回答我的一些问题,但解决了如何获得所需的输出(我认为这对于从事类似于 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"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-13
      • 2019-09-25
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多