【js基礎】之this,call,apply,bind

1.this

this的使用場景:app

  • 1.做爲構造函數執行;
  • 2.做爲對象屬性執行;
  • 3.做爲普通函數執行;
  • 4.call apply bind。
this要在執行時才能確認值,定義時沒法確認
var a = {
    name:"A",
    fn:function(){
        console.log(this.name);
    }
}

a.fn();//this===a

a.fn.call({name:"B"});//this==={name:"B"}

var fn1 = a.fn;
fn1();//this===window

2.call,apply

改變上下文this指向。函數

  • fn.call({this指向},參數1,參數2)
  • fn.apply({this指向},[參數1,參數2])
//call
function fn2(name,age){
    alert(name);//zhangsan
    console.log(this);//{x: 100}
}

fn2.call({x:100},'zhangsan',20);

//apply
function fn3(name,age){
    alert(name);//lisi
    console.log(this);//{y: 200}
}

fn3.apply({y:200},['lisi',30]);

3.bind

在函數表達式後邊改變函數的上下文。this

  • var fn = function(參數){}.bind({this指向});
  • fn(參數)
var fn4 = function(name,age){
    alert(name);//wangwu
    console.log(this);//{z: 300}
}.bind({z:300});

fn4('wangwu',40);
相關文章
相關標籤/搜索