我有一个具有给定构造函数的JavaScript类,并且我希望用户能够使用函数实例化一个对象。我假装的示例如下:
class Car{
constructor(numberWheels, Name, Color){
this.wheelsNum = numberWheels;
this.name = Name;
this.color = Color;
}
}
创建一个使用Car构造函数的函数。使用此函数后,我从对象car编写字符串键:像该函数()一样,让car2 = new Car('numberWheels','Color');然后使用此键创建新对象。
let car1 = new Car (4, 'jeep', 'red');
function ()
let car2 = new Car ('numberWheels', 'Color');
let car22= new Car2(4, 'yellow');
答案 0 :(得分:0)
要创建无名汽车,可以创建一个单独的函数:
function car2(numberWheels, color) { return new Car(numberWheels, undefined, Color); }
const car22 = car2(4, 'yellow');
console.log(car22);
不,您不能通过将字符串传递给构造函数来创建此函数,而实际上不应该。