使用 new 来调用函数,或者说发生构造函数调用时,会自动执行下面的操作。
- 创建(或者说构造)一个全新的对象。
- 这个新对象会被执行 [[ 原型 ]] 连接。
- 这个新对象会绑定到函数调用的 this 。
- 如果函数没有返回其他对象,那么 new 表达式中的函数调用会自动返回这个新对象。
function fn() {
...
}
var p1 = new fn(...)
// 使用 objectFactory模拟new
var p1 = objectFactory(fn, ...)
模拟实现:
function objectFactory() {
var obj = new Object();
construc = [].shift.call(arguments); // 从类数组中取出第一个
obj.__proto__ = construc.prototype;
var res = construc.apply(obj, arguments); // 注意此时的arguments已被取出第一个值
return typeof res === 'object' ? res : obj;
}
// 测试
function fn(name) {
this.name = name;
this.age = 20;
}
var p1 = objectFactory(fn, 'Tom');
console.log(p1.name);
console.log(p1.age);
// 'Tom'
// 20
网友评论