I am trying to set up a javascript object with one of it's items being a function. I am doing a little bit of self reference and it is not working.
var onTimePoints = function($a, $b, $c, $lifeotr){
$var1 = ($b - $a) / $c;
$var2 = ($lifeotr - $a) / $var1;
if($var2>$c)
{
$var2 = $c;
}
if($var2<0)
{
$var2 = 0;
}
$var2 = Math.round($var2);
return $var2;
}
var lifeData ={
min: 25000,
max: 65000,
otr: 56426,
maxPoints:100,
otp: onTimePoints(25000, 65000, 100, 56426),
test: function(){
alert(this.min);
}
}
When I do conosle.log(lifeData.otp) it works.
When I replace the hard coded numbers with this.min, this.max, etc... it doesn't work.
Here is an example of what doesn't work:
var lifeData ={
min: 25000,
max: 65000,
otr: 56426,
maxPoints:100,
otp: onTimePoints(this.min, this.max, this.maxPoints, this.otr),
test: function(){
alert(this.min);
}
}
In this case console.log(lifeData.otp) returns NaN.
I am sure that I am just overlooking something. Appreciate if you know the issue.
thishas nothing whatsoever to do with an under-construction object literal. It has to do solely with function invocation context. Basically there's no direct way to do what you're doing in JavaScript. You have to use a separate statement.thisiswindow, notlifeData.lifeData.test(), it's that function call itself that ensures thatthisinside the function is set to refer to the "lifeData" object. However, that's not the case in the midst of the object literal that initializes the object. In that context,thishas a value determined by the context of thatvardeclaration.lifeData.otp;and you'll see that you get aNaNback.