我是JS的新手,最近我研究了对象和函数。在这里,我想为一个对象数组中的每个对象调用一个函数。我正在使用forEach
这样做。每个属性的结果为undefined
。
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);
每个对象的结果都是这样的:
name: undefined
price: undefined
sold: undefined
console: [object Object]
games.forEach(showDetail);
答案 0 :(得分:4)
你应该将'游戏'作为参数传递给函数并打印其属性,而不是从'this'
function showDetail(game){
console.log(`name: ${game.name}
price: ${game.price}
sold: ${game.sold}`);
}
const games = [ ..... ]
games.forEach( function(game) { showDetail(game) });
//if there is support for arrow functions, it's cleaner
games.forEach( game => showDetail(game) );
//also, as mentioned by Máté in the comments
games.forEach( showDetail ); //will work
如果你想让'showDetail'函数使用'this',你应该将'game'绑定到函数
games.forEach( game => showDetail.bind(game)() );
function showDetail(){
//here the 'this' is the 'game', because it has been bounded via .bind() method
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
答案 1 :(得分:1)
写作时
games.forEach(showDetail);
showDetails是forEach的回调函数,它作为第一个参数传递给对象,因此你会写
function showDetail(game) {
console.log(`name: ${game.name}
price: ${game.price}
sold: ${game.sold}
console: ${game.console}
`);
}
当你在showDetail中this
时,该值为not binded
到对象上下文,因此this.name
不返回对象值。但是,如果你写
games.forEach(game => {
showDetail.call(game);
});
你提供的上下文是对象,这个案例this.name
在showDetail中会起作用
答案 2 :(得分:0)
也许你的意思是
// constructor
function Game(parms) {
this.name = parms.name;
this.price = parms.price;
this.sold = parms.sold;
this.gconsole = parms.gconsole;
}
// toString override
Game.prototype.toString = function() {
return `name: ${this.name}
price: ${this.price}
sold: ${this.sold}
gconsole: ${this.gconsole}
`;
}
const games = [
new Game({
name: ' Crash Bandicoot N. Sane Trilogy',
price: 1060,
sold: 20,
gconsole: 'PS4'
}),
new Game({
name: 'Lego Marvel Super Heroes',
price: 700,
sold: 25,
gconsole: 'XBOX'
}),
new Game({
name: 'Gta V',
price: 1449,
sold: 30,
gconsole: 'PS4'
})
];
games.forEach(function(g) {
console.log(g.toString());
});