我有以下一段JavaScript代码
function freezeProps(o) {
var props = (arguments.length == 1) // If 1 arg
? Object.getOwnPropertyNames(o) // use all props
: Array.prototype.splice.call(arguments, 1); // else named props
props.forEach(function(n) { // Make each one read-only and permanent
// Ignore nonconfigurable properties
if (!Object.getOwnPropertyDescriptor(o,n).configurable) return;
Object.defineProperty(o, n, { writable: false, configurable: false });
});
return o; // So we can keep using it
}
// Make the named (or all) properties of o nonenumerable, if configurable.
function hideProps(o) {
var props = (arguments.length == 1) // If 1 arg
? Object.getOwnPropertyNames(o) // use all props
: Array.prototype.splice.call(arguments, 1); // else named props
props.forEach(function(n) { // Hide each one from the for/in loop
// Ignore nonconfigurable properties
if (!Object.getOwnPropertyDescriptor(o,n).configurable) return;
Object.defineProperty(o, n, { enumerable: false });
});
return o;
}
function Range(from, to) { // Constructor for an immutable Range class
this.from = from;
this.to = to;
freezeProps(this); // Make the properties immutable
}
Range.prototype = hideProps({ // Define prototype with nonenumerable properties
constructor: Range,
includes: function(x) { return this.from <= x && x <= this.to; },
foreach: function(f) {for(var x=Math.ceil(this.from);x<=this.to;x++) f(x);},
toString: function() { return "(" + this.from + "..." + this.to + ")"; }
});
var range = new Range(10, 12);
var result = range.includes(10.9666);
alert(result);
我在函数freezeProps()和hideProps()中无法理解的是,我可以将多个参数传递给hideProps(arg1,arg2,arg3)然后
arguments.length != 1
将执行以下代码行
var props = Array.prototype.splice.call(arguments, 1);
但是道具将包含像[arg2,arg3]这样的结果数组,如果是这样的话,那么为什么仍然可以将对象arg1上的命名属性(从代码中的注释中清楚地看到)更改为不可数。这对我来说没有意义。任何建议都将受到高度赞赏。