JavaScript Objects: Why Doesn't This Work?

  • A+
Category:Languages

I wrote the following code. Instead of giving me an answer, it outputs NaN. I would like the code to return the weights of John and Mark. Please explain.

'use script';  //  Declaring variables var infoJohn; var infoMark; var bmiCalculator; var higherBmi;  bmiCalculator = function (height, mass) {     var calculatedBmi;      calculatedBmi = mass / (height * height);     return calculatedBmi; };  infoJohn = {     name: 'John',     mass: 85,     height: 110,     bmi: bmiCalculator(this.height, this.mass) };  infoMark = {     name: 'Mark',     mass: 120,     height: 85,     bmi: bmiCalculator(this.height, this.mass) };  console.log('Mark/'s BMI: ' + infoMark.bmi, 'John/'s BMI: ' + infoJohn.bmi,  '/n/n'); 

 


You need to wrap bmiCalculator call to a function because otherwise this refers to a global (window) context.

This should work:

var bmiCalculator = function(height, mass) {   var calculatedBmi;    calculatedBmi = mass / (height * height);   return calculatedBmi; };  var infoJohn = {   name: 'John',   mass: 85,   height: 110,   bmi: function() {     return bmiCalculator(this.height, this.mass);   } };  var infoMark = {   name: 'Mark',   mass: 120,   height: 85,   bmi: function() {     return bmiCalculator(this.height, this.mass);   } };  //higherBmi = function (h)  console.log('Mark/'s BMI: ' + infoMark.bmi(), 'John/'s BMI: ' + infoJohn.bmi(),   '/n/n');

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: