如何在另一个函数中使用一个函数的结果?

时间:2015-05-07 21:24:26

标签: javascript

抱歉这就是现在所有这一切......花了一些时间来习惯这个网站。我不知道你们会这么快。就像我说的那样,第一个函数运行正常,所以我不明白为什么我不能在getDonutsPD函数中使用this.DonutsPH。

  function donutStore(location, minCustPh, maxCustPh, averageDpC, hoursOpen) {
      this.location   = location;
      this.minCustPh  = minCustPh;
      this.maxCustPh  = maxCustPh;
      this.averageDpC = averageDpC;
      this.hoursOpen  = hoursOpen;
      this.donutsPerHourValue = 0;
      this.getDonutsPH = function() {
       console.log(this.donutsPerHourValue = (this.location + " needs " + (Math.floor(Math.random() * (this.maxCustPh - this.minCustPh) + this.minCustPh)) * this.averageDpC) + " donuts per hour.");
    };
    this.getDonutsPD = function() {
     console.log(this.getDonutsPH * this.hoursOpen);
    };
     var Downtown    = new donutStore("Downtown",       8, 43, 4.5,  24);
    var CapitolHill = new donutStore("CapitolHill",    4, 37, 2,    12);
    var SLU         = new donutStore("SouthLakeUnion", 9, 23, 6.33, 24);
    var wWood       = new donutStore("WestWood",       2, 28, 1.25, 12);
    var Ballard     = new donutStore("Ballard",        8, 58, 3.75, 16);
    var dNutStores = [Downtown, CapitolHill, SLU, wWood, Ballard];

    for(i=0; i < dNutStores.length; i ++) 
    {
      dNutStores[i].getDonutsPH();
      dNutStores[i].getDonutsPD();
    }

1 个答案:

答案 0 :(得分:3)

this.getDonutsPH是一个变量。在javascript函数中也可以是变量。

为了运行任何功能,您需要将()附加到函数名称,例如

this.getDonutsPH()

第二件事,做一个console.log('blah')不会返回任何值,你需要告诉函数返回一个值

this.getDonutsPH = function() {
    return this.location + " needs " + (Math.floor(Math.random() * (this.maxCustPh - this.minCustPh) + this.minCustPh)) * this.averageDpC) + " donuts per hour.";
}

更新:JoshBeam评论: -

我也要指出,this.getDonutsPH * this.hoursOpen将返回NaN,因为this.getDonutsPH将返回一个字符串。将数字乘以数字将始终返回NaN。