The code below prints only the event contents, how do I make that print WheatherData.value number? I am coming from java and I am used to do it this way.
JavaScript
x
37
37
1
const Event = (time, place) => {
2
var _time = time
3
var _place = place
4
5
return {
6
getTime() {
7
return _time
8
},
9
getPlace() {
10
return _place
11
},
12
updateTime() {
13
_time = new Date(Date.now())
14
},
15
toString() {
16
return 'Time: ' + _time + 'nPlace: ' + _place
17
}
18
}
19
}
20
21
const WeatherData = (value, time, place) => {
22
var _event = Event(time, place)
23
var _value = value
24
const getValue = () => { return _value }
25
const toString = () => { return 'nValue: ' + _value + _event.toString() }
26
return Object.assign({ getValue, toString }, _event)
27
}
28
29
30
31
const wd = WeatherData(10.1, new Date(Date.now()), 'Chisinau, Moldova')
32
33
console.log(wd.toString())
34
35
//Time: Sat Sep 18 2021 08:49:10 GMT+0200 (Central European Summer Time)
36
//Place: Chisinau, Moldova
37
// no value printed
Advertisement
Answer
JavaScript
1
2
1
return Object.assign({ getValue, toString }, _event)
2
The line above causing the problem. When you assign _event
object to { getValue, toString }
object you are simply overriding toString
method of WeatherData
function. Instead, just return { getValue, toString }
from your WeatherData
function, like below;
JavaScript
1
10
10
1
const WeatherData = (value, time, place) => {
2
var _event = Event(time, place);
3
var _value = value
4
5
const getValue = () => { return _value }
6
const toString = () => { return 'nValue: ' + _value + 'n' + _event.toString() }
7
8
return { getValue, toString }
9
}
10