程序员

js基础5(this)

2018-08-27  本文已影响0人  逆_3ec2

1、this的认识

1. 默认绑定
2. 隐式绑定
3. 隐式丢失
  console.log(this); // 指向window
  
  function fun (){
    console.log(this);
  }
  fun(); // 指向window

  //自执行this
  var a = 0;
  var obj = {
    a: 2,
    foo: function (){
      function test (){
        console.log(this.a);
      }
      test();
    }
  }
  obj.foo(); // 指向window

  //闭包中的this
  var a = 0;
  function foo (){
    var a = 2;
    function test (){
      a = 3;
      console.log(this.a);
    }
    return test;
  }
  foo()(); // 指向window

  //隐式绑定
  function fun (){
    console.log(this.a);
  }
  var obj1 = {
    a: 1,
    foo: fun,
    obj2: {
      a: 2,
      foo: fun
    }
  }
  obj1.foo(); // 指向obj1
  obj1.obj2.foo(); // 指向obj2

// 隐式丢失
var a = 0;
function fun (){
  console.log(this.a);
}
var obj1 = {
  a: 1,
  foo: fun
}
obj1.foo(); // 这是一个对象下的方法隐式绑定,所以绑定对象是obj1
var bar = obj1.foo; // 把obj1.foo赋值给bar变量,造成隐式丢失,
// 是因为这个变量和这个对象obj1毫无关系,就是绑定到window
bar(); // 指向window

// 隐式丢失
var b = 0;
var bar1 = function(){  
        var b = 2;
    console.log(this.b);
};
bar1(); // 指向window

// 隐式丢失
var a = 0;
function fun (){
  console.log(this.a);
}
function bar (fun){
    fun();
}
var obj = {
    a: 2,
    foo: fun
}
obj.foo(); // 指向obj,对象方法来执行函数声明,隐式绑定该对象
bar(obj.foo); // 隐式丢失,指向window --- 把函数当参数传递会造成隐式丢失

2、严格模式

开启严格模式:"use strict",避免未声明变量泄露

3、改变this指向

let wrap = document.getElementById("wrap");
     json = {
       a = 2,
       b = 3;
     }

// call()
function fun (x){
  console.log(this.a + this.b);
  console.log(x);
} 
wrap.onclick = fun; // 事件函数this指向调用的这个对象
fun.call(json, 2); // 输出5,2,this指向json,这里的实参2,传递到fun()的形参里面

// apply()
function fun (x, y){
  console.log(this.a + this.b);
  console.log(x + y);
} 
wrap.onclick = fun; // 事件函数this指向调用的这个对象,输出50
fun.apply(json, [3,3]); // this指向json,数组的参数传递到函数fun()的形参里面

// bind()
let json= {
  a: 1,
  b: 2
};
wrap.onclick = fun.bind(json, 20);
function fun (x){
  console.log(this.a);
  console.log(x);
}
上一篇 下一篇

猜你喜欢

热点阅读