I'm new to JS and I recently studied about objects and functions. Here I want to call a function for each object in an array of objects. I'm using forEach
to do so. The result is undefined
for each property.
function showDetail() {
console.log(`name: ${this.name}
price: ${this.price}
sold: ${this.sold}
console: ${this.console}
`);
}
const games = [{
name: ' Crash Bandicoot N. Sane Trilogy',
price: 1060,
sold: 20,
console: 'PS4',
},
{
name: 'Lego Marvel Super Heroes',
price: 700,
sold: 25,
console: 'XBOX',
showDetail: function() {
console.log(this.name);
}
},
{
name: 'Gta V',
price: 1449,
sold: 30,
console: 'PS4',
showDetail: function() {
console.log(this.name);
}
}
];
games.forEach(showDetail);
The result is like this for each object:
name: undefined
price: undefined
sold: undefined
console: [object Object]
games.forEach(showDetail);
games.forEach(i => { showDetail.bind(i)() });
.bind()
like that. If you're calling the function immediately, you use.call
or.apply
to set the value of the thisArg.games.forEach(obj => showDetail.call(obj));