脚本宝典收集整理的这篇文章主要介绍了javascript代码实例教程-js-提前声明和new操作符理解,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
var a=1;
function aheadOfStatement(){
alert(a);
var a=2;
}
这段代码结果是undefined,因为函数aheadOfStatement中的声明了变量a,并覆盖了全局变量a,但是没有赋值。等价于下面的代码:
var a=1;
function aheadOfStatement(){
var a;
alert(a);
a=2;
}
2、new的理解
如果在一个函数前面带上new来调用该函数,那么将创建一个隐藏连接到该函数的prototype成员的新对象,同时this将被绑定到那个新对象上。
实例1:函数没有返回值
复制代码
function testNoReturn(){
var a=1;
}
var test=testNoReturn();
var testWithNew=new testNoReturn();
alert(test); //undefined
alert(testWithNew); //[object Object]
alert(testWithNew instanceof testNoReturn); //true
复制代码
实例2:函数返回基本类型;没有new的,得到a的值,有new的,得到函数testWithReturn的prototype。
复制代码
function testWithReturn(){
var a=1;
return a;
}
var test=testWithReturn();
var testWithNew=new testWithReturn();
alert(test); //1
alert(testWithNew); //[object Object]
alert(testWithNew instanceof testWithReturn); //true
复制代码
实例3:函数返回引用类型;没有new的,得到了Array类型的变量,有new的,也得到了Array类型的变量,而不是得到testWithReturn的prototype。
这个实例中,没有new的,是构造函数的工厂模式;有new的,是构造函数的寄生构造函数模式。
复制代码
function testWithReturn(){
var a=new Array();
a=[1,2,3];
return a;
}
var test=testWithReturn();
var testWithNew=new testWithReturn();
alert(test); //[1,2,3]
alert(testWithNew); //[1,2,3]
alert(testWithNew instanceof testWithReturn); //false
alert(test instanceof Array); //true
alert(testWithNew instanceof Array); //true
//函数返回引用类型后,有没有new,都得到的是引用类型,有了new,也不返回函数的prototype
复制代码
实例4:this绑定;有new的,this指向的是testWithNew。没有this的,指向的是调用testThis的对象,在全局环境中是window。所以可以找到a变量。
复制代码
var a=1;
function testThis(){
alert(this.a);
this.b=2;
}
var test=testThis(); //1
var testWithNew=new testThis();//undefined
alert(testWithNew.b);//2
觉得可用,就经常来吧! 脚本宝典 欢迎评论哦! js脚本,巧夺天工,精雕玉琢。小宝典献丑了!
以上是脚本宝典为你收集整理的javascript代码实例教程-js-提前声明和new操作符理解全部内容,希望文章能够帮你解决javascript代码实例教程-js-提前声明和new操作符理解所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。