手写new操作符时,表达式Array.prototype.shift.call(arguments) 是否可以通过argument[0]代替?-灵析社区

一只臭美的Doggg

我感觉获取第一个参数作为构造函数,arguments[0]就能满足需求,为什么要用shift弹出第一个元素呢?我看了好几个代码要么是 Array.prototype.shift.call(arguments) 要么是[].shift.call(arguments); 不太清楚为什么要这样做。

阅读量:331

点赞量:14

问AI
用 Array.prototype.shift.call(arguments) 的方式更方便获取构造函数的参数,用arguments[0]:这种方式只是获取第一个参数,不会改变 arguments 对象。你用这种方式的话,你还要手动创建一个新的参数数组,这个数组里不包含第一个参数,然后把它再传给构造函数。可以看下面的实现: function myNew() { var Constructor = Array.prototype.shift.call(arguments); var obj = Object.create(Constructor.prototype); var result = Constructor.apply(obj, arguments); return result instanceof Object ? result : obj; } function Person(name, age) { this.name = name; this.age = age; } var person = myNew(Person, 'Alice', 25); console.log(person.name); // 输出: Alice console.log(person.age); // 输出: 25