this 改變this的指向
this是Javascript語言的一個關鍵字。
它代表函式執行時,自動生成的一個內部物件,只能在函式內部使用。比如,
function test(){ this.x = 1; }
this 是當前執行上下文中的一部分。
this永遠指向函式的呼叫者。
隨著函式使用場合的不同,this的值會發生變化。但是有一個總的原則,那就是this指的是,呼叫函式的那個物件。
1.this指向的形式4種
a.如果是一般函式,this指向全域性物件window;
b.在嚴格模式下"use strict",為undefined.
c.物件的方法裡呼叫,this指向呼叫該方法的物件.
d.建構函式裡的this,指向創建出來的例項.
e.在事件處理函式中,this指向觸發事件的DOM物件
//a function bar() { console.log(this);//一般函式,this指向全域性物件window } bar(); //b var foo = function() { "use strict"; console.log(this);//表示使用嚴格模式;在嚴格模式下,為undefined } foo(); //c var name = 'tesla'; var car = { name:"bmw", drive: function() { console.log(this); //object car console.log(this.name); //bmw var that = this;//定義一個that變數來儲存this的值 setTimeout(function(){ //setTimeout是全域性函式 console.log(this); //window console.log(this.name); //tesla console.log(that); //object car console.log(that.name); //bmw },1000); } } car.drive(); //d var name = 'tom'; //宣告一個函式 function person() { console.log(arguments.length); this.name = arguments[0]; this.age = arguments[1]; console.log(this); console.log(this.name); console.log(this.age); } person(); //0 window undefined undefined var tom = new person('amy',20);//2 person -> tom amy 20 //e //先遍歷 '.tr-s' $('.tr-s').each(function (index,item) { //再遍歷 '.tr-s' 下的 'td-t' $(this).find('.td-t').each(function (index_s,item_s) { //index_s 是下標 //item_s 是對應的物件 }) })
2.改變this的指向
在JS中一切皆物件,函式也是物件,既然是物件就有屬性和方法,在JS中所有的方法都有兩個方法call(),apply()
我們可以使用這兩個方法來顯示更改函式中this的指向,
call、apply這兩個函式的共同特點:改變並立即執行。
區別就是傳參方式不同
call是一個一個傳入
apply是傳入一個數組,一次性傳完。
.call(),call(thisScope, arg1, arg2, arg3...)
.apply(), apply(thisScope, [arg1, arg2, arg3...]);兩個引數
在ES5中新增了bind(),該方法也是強制更改this指向
而bind 改變this的指向,返回的是函式
.bind()bind(thisScope, arg1, arg2, arg3...)
但是bind和call、apply的區別是bind更改this後不會立即執行,它會返回一個新函式。
bind傳參也是一個一個的傳入
var obj = { name:'tom', age:20 } function show(a,b){ console.log(a,b); } //獨立呼叫 show(1,2); //強制更改this指向為obj 並立即執行該函式 show.call(obj,1,2); show.apply(obj,[1,2]); //強制更改this指向obj,不會立即執行,它會返回一個新函式,需要主動去執行這個函式 show.bind(obj,1,2)();