js理解

js-提前声明和new操作符理解

 

1、提前声明:声明变量后,js会把声明部分提前到作用域前面。

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
复制代码

ps:

观此博文(http://www.cnblogs.com/RitaRichard/archive/2011/10/12/2208902.html)有感,只想记录知识点,实例大部分与其相似,望原作者见谅。

 
 
分类: 前端学习
原文地址:https://www.cnblogs.com/Leo_wl/p/3636994.html