我正在处理一个问题集,我想设置选项而不必发送所有参数。我有大部分工作,但想知道我是否可以设置默认选项,即使没有设置为属性,它将自动成为对象的一部分?这是我的示例,您将看到我有一个门的默认选项,但它没有显示在myCar
对象中。我很感激我在这里做错了什么,以及如何让它正常工作。
CarPrototype = function(options) {
var options = options || {};
name = options.name;
year = options.year;
doors = 4 || options.doors;
make = options.make;
return options;
}
var myCar = CarPrototype({
name: 'Ferarri',
year: 1975,
make: 'f50'
}};
console.log(myCar); // was hoping that doors would be part of this with default?
console.log(myCar.doors); // nothing returned :-(
答案 0 :(得分:3)
此语法无效:
var options = options | {};
使用或运算符||
代替:
function Car (options) {
var options = options || {};
this.name = options.name;
this.year = options.year;
this.doors = options.doors || 4;
this.make = options.make;
}
var car = new Car({name:'vanquish'});
#=> Car {name: "vanquish", year: undefined, doors: 4, make: undefined}
答案 1 :(得分:2)
doors = 4 || options.doors
应该是
doors = options.doors || 4
从左到右阅读表达式。如果左手返回true,则永远不会评估OR的右手。