我有一个Javascript类(使用John Resig's approach)我创建了一个实例并传递了一个args
对象,如下所示:
var myCucumber = new Cucumber({
size: 'small'
organic: true
})
在类本身中,它引用args
对象上的许多属性。但是,没有一个属性是强制性的,因此有时可能会丢失一些属性,这会导致“属性未定义”错误。
要解决此问题,我会执行以下操作:
args.size = args.size || null;
args.organic = args.organic || false;
args.colour = args.colour || null;
args.origin = args.origin || null;
对于可能在整个班级中使用的每个属性,这似乎有点烦人。
如果在创建类的实例时尚未传入args的任何属性,是否有一种干净的方法可以假设args的任何属性都是null
?
答案 0 :(得分:2)
我建议添加一个以预期方式处理值的函数。
示例:
Cucumber.prototype._args = function(attr) {
return this.args[attr] || null;
}
// Then you may use it to access values as follows:
this._args('size');
答案 1 :(得分:1)
尝试这样的事情:
for (var key in args.keys()) {
args[key] = args[key] || null;
}
这是因为每个对象都有一个keys()
函数,它返回该对象的键数组。
参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
答案 2 :(得分:1)
你有几种方法可以做到这一点,但是我不会使用Resig方法,因为它在ES5中存在问题Is John Resig's Javascript inheritance snippet deprecated?
1)(Resig)创建一个构造函数并为所有不存在的属性赋值:
var Cucumber = Class.extend({
{
init: function(args){
this.size = null;
this.organic = false;
//etc
for (var key in args.keys()) {
this[key] = args[key];
}
},
}
2)第二个选项使用带有描述符的Object.create。这使您能够使用默认值创建对象属性。
// Example where we create an object with a couple of sample properties.
// (Note that the second parameter maps keys to *property descriptors*.)
o = Object.create(Object.prototype, {
// foo is a regular 'value property'
size: { writable: true, configurable: true, value: null },
});
3)同时使用Object.defineProperty
我更喜欢后两种方式,因为我认为使用Object.create / Object.defineProperty更清楚,更好,这里有一些关于此事的其他信息:
http://jaxenter.com/a-modern-approach-to-object-creation-in-javascript-107304.html
Understanding the difference between Object.create() and new SomeFunction()
答案 3 :(得分:0)
您可以在引用之前检查是否已设置任何对象属性,例如@adeneo建议。
如果您的对象有很长的属性列表,您可以使用@ aliasm2k的解决方案。
或者您可以编写对象构造函数并使用它。例如
function ToothPaste(color = null, flavor = null, amount = null){
this.color = color;
this.flavor = flavor;
this.amount = amount;
}
var myTp = new ToothPaste('white');
alert(myTp.color);
alert(myTp.flavor);
alert(myTp.amount);