用 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