【发布时间】:2021-12-13 21:29:02
【问题描述】:
以下构造函数和日志代码给出...
function Car(brand, year, model, color, utilidad) {
this.brand = brand;
this.year = year;
this.model = model;
this.color = color;
this.utilidad = utilidad;
this.useFor = (prmt) => {
this.utilidad.push(prmt);
}
};
const toyota = new Car("Toyota", 2021, "Prado", "Red", "city");
toyota.useFor('mountain');
console.log(toyota);
代码没有得到预期的日志数据,而是显示以下消息...
TypeError: "this.utilidad.push is not a function"
为什么会这样?
【问题讨论】:
-
utilidadis not an array -
OP 没有构建原型,而是实现了一个函数,该函数旨在用作构造函数以创建
Car实例。最重要的是,OP 使用错误输入的utilidad参数初始化toyota,该参数应该是一个数组而不是一个字符串,以便允许useFor方法稍后推入对象自己的utilidad属性。
标签: javascript methods constructor instance instantiation