I am creating an object in JavaScript that holds employee information (name, rate, hours, gross pay). In order to calculate the gross, I need to multiply the hours times the rate. My teacher says I should be able to do it right inside my object, but it is not working. Here is my code:
const emp1 = {
name: "John Doe",
rate: 13.25,
hours: 20.25,
gross: rate * hours
};
In javascript you can define functions (methods) on an object and call them as you need :)
Note the method syntax, and the use of 'this' to refer to properties on the object itself.
var emp1 = {
name: "John Doe",
rate: 13.25,
hours: 20.25,
gross: function () {
return this.rate*this.hours
}
};
console.log(emp1.gross())
Another way was to use the get syntax ...
const emp1 = {
name: "John Doe",
rate: 13.25,
hours: 20.25,
get gross () { return this.rate * this.hours; },
};
console.log('emp1.gross ...', emp1.gross);
Thus the idea of cause is the same like what James McGlone did suggest, one just is free of omitting the call operator when accessing the value of this (computed) property.
Both solutions are equally valid, one just does not know which one will please the teacher.
You need to declare the variables outside the object first
var rates = 13.25
var hours = 20.25
var emp1 = {
name : "John Doe",
rates,
hours,
gross: rates * hours
}