重点是arguments
是一个类似数组的对象。正在做 ...
instance.init(arguments);
...传递一个参数,该参数是一个包含某些参数的类似数组的对象。另一方面,做...
instance.init.apply(instance, arguments);
...将传递类似数组的对象作为单独的参数。确实如此设定instance
有点没用,因为你已经写了它,但如果使用.apply
你只需要设置this
值也。
差异的简单示例:
function log(a, b, c) {
console.log(a, b, c);
}
function log2() {
log.apply(null, arguments); // `this` value is not meaningful here,
// it's about `arguments`
}
function log3() {
log(arguments);
}
log(1, 2, 3); // logs: 1, 2, 3
log2(1, 2, 3); // logs: 1, 2, 3
log3(1, 2, 3); // logs: <Arguments>, undefined, undefined
// where <Arguments> contains the values 1, 2, 3