JavaScript中new是用来创建对象实例的.
new开辟了一个空间用来储存构造函数中初始化的数据,并把地址作为返回值返回
如果没有new,构造函数中的this指向全局变量,没有返回值,会显示undefined.
<script>
function Stu(name,age){
this.name=name;
this.age=age;
document.write(this.constructor.name);
}
var a=Stu("s",20);//Window(全局变量)
var b=new Stu("s",20);//Stu
document.write(a);//undefined
document.write(age);//20
document.write(b.age)//20
</script>
new实现的具体步骤:
1.创建一个空对象(即{});
2.将构造函数链接到这个对象上(即改变this链接的对象)
3.在该对象内实现构造函数
4.返回该对象