new的模拟实现(完整版)
new 实现的完整代码
function newFunction () {
//创建一个新对象
var res = new Object();
// 排除第一个构造函数参数,arguments个数发生了改变
var construct = [].shift.call(arguments);
res.__proto__ = construct.prototype;
// 使用apply执行构造函数,将构造函数的属性挂载在res上面
var conres = construct.apply(res, arguments);
// 判断返回类型
return conres instanceof Object ? conres : res;
}
测试
function Animal (name) {
this.name = name;
//如果构造函数 return 了一个对象,那么 new 操作后返回的是构造函数return的对象。
// return {
// props : 'test'
// }
}
Animal.prototype.sayName = function () {
console.log('I am ' + this.name);
}
// (相当于)new 操作符实例化了一个对象;
var cat = newFunction(Animal,'Tom');
console.log(cat.name);
// console.log(cat.props);
console.log(cat);
console.log(cat.__proto__ === Animal.prototype);
cat.sayName();
!!!!!!!!!!!!!!!!!!!!!!