我有一个明确的班级"汽车"我需要添加一个接受布尔参数的函数,并根据输入生成输出。我的想法是在Automobile类中定义函数:
function Automobile(year, make, model, type) {
this.year = year; //integer (ex. 2001, 1995)
this.make = make; //string (ex. Honda, Ford)
this.model = model; //string (ex. Accord, Focus)
this.type = type; //string (ex. Pickup, SUV)
function logMe(boolAnswer) {
if (boolAnswer == true) {
console.log(this.year + ' ' + this.make + ' ' + this.model + ' ' + this.type);
} else {
console.log(this.year + ' ' + this.make + ' ' + this.model);
}
};
}
var automobiles = [
new Automobile(1995, "Honda", "Accord", "Sedan"),
new Automobile(1990, "Ford", "F-150", "Pickup"),
new Automobile(2000, "GMC", "Tahoe", "SUV"),
new Automobile(2010, "Toyota", "Tacoma", "Pickup"),
new Automobile(2005, "Lotus", "Elise", "Roadster"),
new Automobile(2008, "Subaru", "Outback", "Wagon")
];
然后通过调用:
对汽车进行排序并打印已排序的数组var newArray = sortArr(yearComparator, automobiles);
newArray.forEach(logMe(true));
然而,当我这样做时,它表示没有定义logMe。我是否需要更改我定义logMe的方式并使其成为原型?我很困惑如何在汽车中定义这个功能?
答案 0 :(得分:0)
您需要将logMe
设置为this
上的属性,就像数据一样:
this.logMe = function logMe(boolAnswer) {
然后该功能仍然无法从外部获得。您需要从值中实际获得它:
newArray.forEach((obj) => obj.logMe(true));
或者,如果您选择使用prototype
机制,则可以将logMe
移到构造函数之外:
Automobile.prototype.logMe = function logMe() { ...
然后你可以直接在forEach
中使用它:
newArray.forEach(Automobile.prototype.logMe)
但是如果你想传递一个参数,你需要更精细的摆弄,所以我只能留在lambda。
正如 @plalx 指出的那样,logMe
函数不属于此处。如果有的话,toString
将是更好的选择;然后你可以使用该值来实际记录对象。