【发布时间】:2016-10-21 00:08:03
【问题描述】:
我正在尝试实现对 forEach 的简单调用,以在汽车数组中的所有项目上运行 logMe 函数。输出是意外的。所有变量都读取“未定义”。
function Automobile(year, make, model, type) {
this.year = year;
this.make = make;
this.model = model;
this.type = type;
}
Automobile.prototype.logMe = function(boolVal) {
if (boolVal == true) {
console.log(this.year + ' ' + this.make + ' ' + this.model + ' ' + this.type);
} else {
console.log(this.year + ' ' + this.make + ' ' + this.model);
}
}
var automobiles = [
new Automobile(2010, "Toyota", "Tacoma", "Pickup"),
new Automobile(2005, "Lotus", "Elise", "Roadster"),
new Automobile(2008, "Subaru", "Outback", "Wagon")
];
automobiles.forEach(Automobile.prototype.logMe.bind(true)); //the problem
automobiles[0].logMe(true); //test logMe function
输出:
未定义未定义未定义
未定义未定义未定义
未定义未定义未定义
1995 年本田雅阁轿车
【问题讨论】:
标签: javascript arrays foreach