如何从Javascript中的另一个私有方法访问私有方法

时间:2011-07-08 20:13:29

标签: javascript oop private

我想知道是否可以在Javascript上从另一个私有方法调用私有方法。我有一些代码如下:

function Balloon() {
function density( altitude, gas ) {
  /* KG/CU M */

  var gas = { 
   /* GAS DEFINATIONS - wolframalpha.com */
   "hydrogen" : .00100794,
   "helium"   : .004002602,
   "nitrogen" : .0140067,
   "methane"  : .0160425,
   "ammonia"  : .0170305,
   "neon"     : .0201791,
   "dry air"  : .0289644 
  }

  var alt = {
   /* CONSTANTS - http://en.wikipedia.org/wiki/Density_of_air#Altitude */
   "p0" : 101325,   // Sea level standard atmospheric pressure (Pa)
   "T0" : 288.15,   // Sea level standard temperature (K) 
   "g"  : 9.80665,  // Earth-surface gravitational acceleration (m/s^2)
   "L"  : 0.0065,   // Temperature lapse rate (K/m)
   "R"  : 8.31447   // Universal gas constant (mol * K)
  }

  var temperature = alt["T0"] - alt["L"] * altitude;
  var pressure    = alt["p0"] * (1 - (( alt["L"] * altitude ) / alt["T0"] )) ^ (( alt["g"] * gas[gas] ) / ( alt["R"] * alt["L"] ));
  var density     = ( pressure * gas[gas] ) / ( alt["R"] * temperature );

  return density;
 }

 function lift( altitude, gas ) {
  /* KG/CU M */

  return density( altitude, "dry air" ) - density( altitude, gas ); 
 }

 this.requiredGas = function( altitude, gas, ratio, weight ) {
  return (( weight / 1000 ) * ratio ) / lift( altitude, gas );
 }
}

我正试图像访问它一样:

balloon = new Balloon();
var required = balloon.requiredGas(10, "helium", 1.5, 4530);

我看到人们在私人函数like so之外声明this,但不知道是否如何处理此问题。

3 个答案:

答案 0 :(得分:5)

您将使用density数组覆盖传递到gas函数的参数。

看,一旦我重命名它就可以了!

http://jsfiddle.net/pEcMJ/

答案 1 :(得分:2)

您正在使用对象function density( altitude, gas )

重新定义方法参数var gas ={}

答案 2 :(得分:1)

此行生成NAN

var pressure    = alt["p0"] * (1 - (( alt["L"] * altitude ) / alt["T0"] )) ^ (( alt["g"] * gas[gas] ) / ( alt["R"] * alt["L"] )); 

gas[gas]:)