答案 0 :(得分:0)
您可以这样做(甚至向其中添加自定义属性并指定其属性):
class Car {
constructor() {}
}
const car = new Car()
console.log(car)
function carFactory() {
const ret = Object.create(
Car.prototype, {
someAddedProp: {
writable: true,
configurable: true,
value: 'hello'
},
someAddedReadOnlyProp: {
writable: false,
configurable: true,
value: "You can't change me!!!"
},
}
);
return ret;
}
const anotherCar = carFactory();
console.log(anotherCar)
使用Object.create不会调用构造函数,但是您可以使用Object.create的第二个参数来设置属性
答案 1 :(得分:0)
尝试以下代码,我认为您正在尝试实现以下目标:
class Car{
constructor(name){
this.name = name;
}
}
console.log("Car:",new Car("ferrari"));
function makeCar(name){
return new Car(name);
}
console.log("Car:",makeCar("bugatti"));