《javascript高级编程》里对new操作符的解释:
new操作符会让构造函数产生如下变化:
1. 创建一个新对象;
2. 将构造函数的作用域赋给新对象(因此this就指向了这个新对象);
3. 执行构造函数中的代码(为这个新对象添加属性);
4. 返回新对象
/*
Constr:构造函数
args:初始化参数
*/
function newOperator(Constr, args) {
var thisValue = Object.create(Constr.prototype); // 以构造函数的原型对象新建一个新对象
var result = Constr.apply(thisValue, args);//把构造函数的this指向新对象,并为新函数添加新属性
if (typeof result === 'object' && result !== null) {
return result; // 返回新对象
}
return thisValue;
}
看看这段代码的结果
var a=5;
function test(){
a=0;
alert(a);
alert(this.a);
var a;
alert(a);
}
test();
new test();
0
5
0
0
undefined
0
再看看这段代码的结果
var a=5;
function test(){
this.a=0;
alert(a);
alert(this.a);
var a;
alert(a);
}
test();
new test();
undefined
0
undefined undefined 0
undefined
这段代码可以解释为定义var a;那么a就是函数的局部变量,只能在他的活动对象里面找,当执行test()时,this.a相当于window.a;当执行new test()时,this.a这相当于新对象的属性,而a还是test函数的局部变量,跟新对象没关系