JavaScript 工厂函数的正确语法是什么? JavaScript 工厂函数语法混乱
What is the correct syntax of JavaScript Factory Function? JavaScript Factory Function Syntax confusion
函数 getMyCar1 和 getMyCar2 的结果相同,但是哪一个是正确的做法?
getMycar2:为什么必须使用值而不是键? key:value(汽车品牌:品牌)。
function selectCar(brand, model, color){
return{
carBrand: brand,
carModel: model,
carColor: color,
getMyCar1: function(){
return this.carBrand + " " + this.carModel + " " + this.carColor;
//It is said that no need this key word with factory function
//but without this key word not working, why?
},
getMyCar2: function(){
return brand + " " + model + " " + color;
//NotWorking: return carBrand + carModel + carColor
}
};
}
let bmw = selectCar("bmw", "X6", "White");
console.log("My Car Model is: " + bmw.getMyCar1());
let audi = selectCar("Audi", "A8", "Red");
console.log("My Car Model is: " + audi.getMyCar2());
这取决于你想要达到的目标。 IE。,
如果您希望该函数 return 汽车实例的当前状态,您可以使用 getMycar1 函数:
示例:
let bmw = selectCar("bmw", "X6", "White");
bmw.carColor= "black"
console.log("My Car Model is: " + bmw.getMyCar2());
结果是:
My Car Model is: bmw X6 black
这里我们改变了汽车颜色并反映在函数中。
另一方面,如果您想要一种显示汽车初始状态的方法,getMyCar2 函数适合您,因为它会更改汽车属性。
let audi = selectCar("Audi", "A8", "Red");
audi.carColor = 'black'
console.log("My Car Model is: " + audi.getMyCar2());
My Car Model is: Audi A8 Red
getMyCar2 函数使用传递给函数的参数作为值,因此当汽车实例中的任何属性发生更改时不会更改其输出
函数 getMyCar1 和 getMyCar2 的结果相同,但是哪一个是正确的做法?
getMycar2:为什么必须使用值而不是键? key:value(汽车品牌:品牌)。
function selectCar(brand, model, color){
return{
carBrand: brand,
carModel: model,
carColor: color,
getMyCar1: function(){
return this.carBrand + " " + this.carModel + " " + this.carColor;
//It is said that no need this key word with factory function
//but without this key word not working, why?
},
getMyCar2: function(){
return brand + " " + model + " " + color;
//NotWorking: return carBrand + carModel + carColor
}
};
}
let bmw = selectCar("bmw", "X6", "White");
console.log("My Car Model is: " + bmw.getMyCar1());
let audi = selectCar("Audi", "A8", "Red");
console.log("My Car Model is: " + audi.getMyCar2());
这取决于你想要达到的目标。 IE。, 如果您希望该函数 return 汽车实例的当前状态,您可以使用 getMycar1 函数: 示例:
let bmw = selectCar("bmw", "X6", "White");
bmw.carColor= "black"
console.log("My Car Model is: " + bmw.getMyCar2());
结果是:
My Car Model is: bmw X6 black
这里我们改变了汽车颜色并反映在函数中。
另一方面,如果您想要一种显示汽车初始状态的方法,getMyCar2 函数适合您,因为它会更改汽车属性。
let audi = selectCar("Audi", "A8", "Red");
audi.carColor = 'black'
console.log("My Car Model is: " + audi.getMyCar2());
My Car Model is: Audi A8 Red
getMyCar2 函数使用传递给函数的参数作为值,因此当汽车实例中的任何属性发生更改时不会更改其输出