JavaScript工厂功能的正确语法是什么? JavaScript工厂功能语法混乱
两者都函数getMyCar1& GetMyCar2具有相同的结果,但是哪一种是正确的方法?
getMyCar2:为什么值必须使用而不是键?钥匙:价值(Carbrand:Brand)。
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
}
};
}
让BMW = SelectCar(“ BMW”,“ X6”,“ White”);
console.log(“我的汽车模型是:” + bmw.getmycar1());
让audi = selectcar(“ audi”,“ a8”,“ red”);
console.log(“我的汽车模型是:” + audi.getmycar2());
Both function getMyCar1 & getMyCar2 has same result but which one is the correct way of doing?
getMycar2: Why value have to use instead of key? key:value (carBrand:brand).
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());
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这取决于您要实现的目标。 IE,
如果您希望该功能返回汽车实例的当前状态,则具有 getMyCar1 函数:
示例:
结果是:
,我们更改了汽车颜色,并反映在功能中。
另一方面,如果您想要一种显示汽车初始状态的方法, getMyCar2 功能适合您,因为它确实会更改汽车属性。
getMyCar2 函数使用将函数传递给该函数的参数,因此当在汽车实例中更改任何属性时不会更改其输出
It depends on what you want to achieve. i.e.,
If you want that function to return the current state of a car instance, you have getMycar1 function:
Example:
Result is:
Here we changed car color and is reflected in the function.
on the other hand if you want a method to show initial state of car, getMyCar2 function is for you as it does change car attributes.
getMyCar2 function uses parameters passed to the function as values and so doesnt change its output when any attribute is changed in a car instance