我读过这本书,当然,使用构造函数在创建更多对象时会更好,并且被告知要少打字,但到了本章末尾,它提供了另一种选择来创建实际上需要大量打字的对象让我感觉只是以不同的方式创建一个对象文字。
以汽车对象为例:
function Car(make, model, year, color, passengers, convertible, mileage){
this.make = make;
this.model = model;
this.year = year;
this.color = color;
this.passengers = passengers;
this.convertible = convertible;
this.mileage = mileage;
this.started = false;
this.start = function(){
this.started = true;
};
this.stop = function(){
this.started = false;
};
this.drive = function(){
if(this.started){
console.log(this.make + " " + this.model + " goes zoom zoom!");
}else{
console.log("Start the engine first.");
}
}
}
创建新的汽车对象
var chevy = new Car("Chevy", "Bel Air", 1957, "red", 2, false, 1021);
var cadi = new Car("GM", "Cadillac", 1955, "tan", 5, false, 12892);
var taxi = new Car("Webville Motors", "Taxi", 1955, "yellow", 4, false, 281341);
var fiat = new Car("Fiat", "500", 1957, "Medium Blue", 2, false, 88000);
var testCar = new Car("Webville Motors", "Test Car", 2014, "marine", 2, true, 21)
我可以理解以上所有内容,但是这本书建议了一种更好的另一种需要更多输入的方法是将这些参数存储到另一个变量中并像这样更改构造函数
function Car(params){
this.make = params.make;
this.model = params.model;
this.year = params.year;
this.color = params.color;
this.passengers = params.passengers;
this.convertible = params.convertible;
this.mileage = params.mileage;
this.started = false;
this.start = function(){
this.started = true;
};
this.stop = function(){
this.started = false;
};
this.drive = function(){
if(this.started){
console.log(this.make + " " + this.model + " goes zoom zoom!");
}else{
console.log("Start the engine first.");
}
}
}
var chevyParam = {
make: "Chevy",
model: "Bel Air",
year: 1957,
color: "red",
passengers: 2,
convertible: false,
mileage: 1021
}
var chevy = new Car(chevyParam);
就像我了解正在发生的事情以及它是如何工作的一样,但是第二个真的比第一个更好、更整洁吗?我知道第二个不必关心是否以错误的顺序输入参数,但还有更多工作
最佳答案
两种方法都很好。 “好”意味着“具有特定 Angular 色所需的品质”。据谷歌称。如果能满足你的需求就好了。
然而,大多数编程社区通常不同意某些做事方法,因为它们不明确(不可读)或 hacky。你所描述的这两种方法既不是hacky也不是不明确,它们只是满足不同的需求。
方法一:
可读性较差
混合变量可能会更容易,并且对于审查您的代码的人来说并不明显。
短多了
我个人认为对于属性较少的简单对象,第一种方法最合适。
方法2:
可读性强
可以说混合变量更困难,并且对于审查您的代码的人来说更明显。
有点长
对于更复杂的对象(例如汽车),您可能需要使用第二种方法,因为它更明确,并且值可以乱序而不会破坏任何内容。
还可以考虑通过这样做添加默认值:this.model = params.model || “如果 params.model 未定义,则默认模型”;
关于javascript - 这种创建对象的方式真的更好吗? (javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35160373/