Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Objects: Why Doesn't This Work?

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');
like image 824
Jachi Avatar asked Aug 21 '18 06:08

Jachi


People also ask

Why this keyword is undefined in JavaScript?

A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .

How does objects work in JavaScript?

JavaScript is designed on a simple object-based paradigm. An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method.

Why JavaScript is not object oriented?

JavaScript is Object-Based, not Object-Oriented. The difference is that Object-Based languages don't support proper inheritance, whereas Object-Oriented ones do. There is a way to achieve 'normal' inheritance in JavaScript (Reference here), but the basic model is based on prototyping. Save this answer.

How do you call an object in JavaScript?

The call() method is a predefined JavaScript method. It can be used to invoke (call) a method with an owner object as an argument (parameter). With call() , an object can use a method belonging to another object.


1 Answers

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');
like image 101
ymd Avatar answered Sep 22 '22 01:09

ymd