javascript易错总结

2017-09-08  本文已影响0人  克里斯加德纳

变量的作用域

var a = 1;
function test(){
    var  a = 2;
    console.log(a);//2
}

上面test函数的作用域中声明并赋值了a,且在console之上,所以遵循就近原则输出a等于2;

var a = 1;
function test(){
   console.log(a);//undefined
   var a = 2;
}

上面的函数作用于虽然在函数作用域中声明并赋值了a,但位于console之下,a变量被提升,输出时,已声明但是未被赋值,所以输出undefine

var a = 1;
function test(){
   console.log(a); //1
   a = 2;
}

上面函数作用域中a被重新赋值,未被重新声明,且位于console之下,所以输出全局作用域的a;

let b = 1;
function test(){
   console.log(b);// b is not define;
   let b = 2;
}

上面函数作用域使用了ES6的let重新声明变量b,而let不同于var其不存在变量提升功能,所以输出报错 b is not define

function test(){
   let a = 1;
  {
      let a = 2;
  }
   console.log(a);//1
}

上面的函数作用let为a声明为1,并在块级作用域中声明a 为2,因为console并不在函数的块级作用域里,所以输出1

类型比较

 var arr = [],
       arr2 = [1];
console.log(arr === arr2); //false

不同数组比较都为false

var arr = [],
      arr2 = [];
console.log(arr ===arr2); //false

两个不同的数组比较,由于两个单独的数组永远不会相等,所以console为false;

var arr=[],arr2=[];
console.log(typeof(arr)===typeof(arr2));//true

利用typeof比较数组对象,因为typeof获取NULL、数组、对象的类型都为object、所以console为true;

var arr = [];
console.log(arr instanceof Object);//true
console.log(arr instanceof Array); //true

使用instanceof判断一个变量是否属于某个对象的实例,因为在JavaScript中数组也是对象的一种,所以两个console都是true

this的指向 H1

this是Javascript语言的一个关键字它代表函数运行时,自动生成的一个内部对象,只能在函数内部使用
随着函数使用场合的不同,this的指向会发生变化。但是有一个总的原则,那就是this指的是,调用函数的那个对象。 一般会分为以下四种情况

纯粹的函数调用 H2

var x = 1; 

  function test(){ 

    cosole.log(this.x); 

  } 

test(); // 1 

上面是函数的最通常用法,属于全局性调用,因此this就代表全局对象Global。 所以输出结果为1

作为方法调用的对象使用 H2

function test(){ 

   console.log(this.x); 

  } 
var o = {}; 
o.x = 1; 
o.m = test; 
o.m(); // 1 

上面的console.log(this.x)的this指向的是对象o;

作为构造函数使用 H2

 function test(){ 

    this.x = 1; 

  } 

 var o = new test(); 

 console.log(o.x); // 1 

所谓构造函数,就是通过这个函数生成一个新对象(object)。这时,this就指这个新对象。

var x = 2; 

 function test(){ 

    this.x = 1; 

 } 

 var o = new test(); 

 console.log(x); //2 

运行结果为2,表明这时this不是全局对象,所以全局变量x的值根本没变。

apply调用

 var x = 0; 

  function test(){ 

   console.log(this.x); 

  } 

  var o={}; 

  o.x = 1; 

  o.m = test; 

  o.m.apply(); //0 

apply()是函数对象的一个方法,它的作用是改变函数的调用对象,它的第一个参数就表示改变后的调用这个函数的对象。因此,this指的就是这第一个参数。
apply()的参数为空时,默认调用全局对象。因此,这时的运行结果为0,证明this指的是全局对象。

o.m.apply(o); //1

如果把最后一行代码修改为上面代码,运行结果就变成了1,证明了这时this代表的是对象o

上一篇 下一篇

猜你喜欢

热点阅读