this的使用場景:app
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
改變上下文this指向。函數
//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]);
在函數表達式後邊改變函數的上下文。this
var fn4 = function(name,age){ alert(name);//wangwu console.log(this);//{z: 300} }.bind({z:300}); fn4('wangwu',40);