【发布时间】:2012-12-14 14:03:05
【问题描述】:
我正在尝试在 JavaScript 中创建一个小型结构,我将在画布库中使用它。我希望创建此结构时传递的参数是像我们在编译语言中那样的多个参数,或者是具有与这些参数对应的属性的对象:
BoundingBox = function( x, y, w, h ) {
if( 'object' === typeof x ) {
if( ! 'x' in x ) throw new Error('Property "x" missing');
if( ! 'y' in x ) throw new Error('Property "y" missing');
if( ! 'w' in x ) throw new Error('Property "w" missing');
if( ! 'h' in x ) throw new Error('Property "h" missing');
this.x = x.x;
this.y = x.y;
this.w = x.w;
this.h = x.h;
} else {
if( null == x ) throw new Error('Parameter 1 is missing');
if( null == y ) throw new Error('Parameter 2 is missing');
if( null == w ) throw new Error('Parameter 3 is missing');
if( null == h ) throw new Error('Parameter 4 is missing');
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
};
然后:
var bb1 = new BoundingBox(0, 0, 200, 100);
var bb2 = new BoundingBox({
x: 0,
y: 0,
w: 200,
h: 100
});
var bb3 = new BoundingBox(bb2);
这是一种干净的方法吗?在我们使用对象的情况下,使用“x”作为对象似乎很奇怪。
我还有第二个问题: 所有这些错误检查都值得付出努力吗?它使代码的大小加倍,使其读取和写入的时间更长,并且由于属性是公共的,因此不能完全防止出现空值或未定义值。
感谢您的帮助:)
【问题讨论】:
-
您可以创建一个简单的
overload函数,其签名如(func, types, newFunc),其中types是新声明函数的typeof值数组。然后,您可以分离重载逻辑和不同的功能。 -
感谢您的回答。我不确定你的想法。
标签: javascript object error-handling arguments