JavaScript
里的new
关键字
new
做了如下5件事情:
1. 创建了一个新的object
2. 设置这个新的object
的 internal, inaccessible, prototype 属性为构造器的 internal, accessible, prototype 对象
3. 使this
变量指向这个新创建的object
4. 执行构造器函数
5. 返回新创建的object
下面这段代码也许解释得更清楚:
function New(func) {
var res = {};
if (func.prototype !== null) {
res.__proto__ = func.prototype;
}
var ret = func.apply(res, Array.prototype.slice.call(arguments, 1));
if ((typeof ret === "object" || typeof ret === "function") && ret !== null) {
return ret;
}
return res;
}