new 为一元运算符
作用:后面只能跟函数,用来调用函数
使用new调用函数与直接调用函数的区别:
function fn1(){ console.log(this); } //this指向的变化 var ret1 = fn1();// Window var ret2 = new fn1();//fn1{} //返回值的变化没有return console.log("ret1:"+ret1);//ret1:undefined console.log("ret2:"+ret2);//ret2:[object Object] //返回值的变化有return 返回对象 function fn2(){ return ["summer","autumn"]; } var ret3 = fn2(); var ret4 = new fn2(); console.log("ret3:"+ret3);//et3:summer,autumn console.log("ret4:"+ret4);//ret4:summer,autumn //返回值的变化有return 返回非对象 function fn3(){ return "我是字符串"; } var ret5 = fn3(); var ret6 = new fn3(); console.log("ret5:"+ret5);//ret5:我是字符串 console.log("ret6:"+ret6);//ret6:[object Object]
使用new调用函数可以改变 this 的指向,返回值始终是一个对象。