在具體的實際應用中,this 的指向無法在函數(shù)定義時確定,而是在函數(shù)執(zhí)行的時候才確定的,根據(jù)執(zhí)行時的環(huán)境大致可以分為以下3種:
1、當函數(shù)作為普通函數(shù)調用時,this 指向全局對象
2、當函數(shù)作為對象的方法調用時,this 指向該對象
3、當函數(shù)作為構造器調用時,this 指向新創(chuàng)建的對象
示例一:
window.name = 'myname';function getName() { console.log(this.name);}getName(); //輸出myname示例二:
var boy = { name: 'Bob', getName: function() { console.log(this.name); }}boy.getName(); //輸出Bob示例三:
function Boy(name) { this.name = name;}var boy1 = new Boy('Bob');console.log(boy1.name); //輸出Bob對于示例三,還有一種特殊情況,就是當構造函數(shù)通過 "return" 返回的是一個對象的時候,此次運算的最終結果返回的就是這個對象,而不是新創(chuàng)建的對象,因此 this 在這種情況下并沒有什么用。
示例四:
function Boy(name) { this.name = name; return { //返回一個對象 name: 'Jack' }}var boy1 = new Boy('Bob');console.log(boy1.name); //輸出Jack示例五:
function Boy(name) { this.name = name; return 1; //返回非對象}var boy1 = new Boy('Bob');console.log(boy1.name); //輸出Bobcall 和 apply 的作用
apply 接受兩個參數(shù),第一個參數(shù)指定了函數(shù)體內 this 的指向,第二個參數(shù)是一個數(shù)組或類數(shù)組,用于傳遞被調用函數(shù)的參數(shù)列表。
示例一:
function getInfo() { console.log(this.name+' like '+arguments[0]+' and '+arguments[1]);}var boy1 = { name: 'Bob', age: 12}getInfo.apply(boy1,['sing','swimming']); //輸出Bob like sing and swimmingcall 傳入?yún)?shù)的數(shù)量是不固定的,跟 apply 相同的是,第一個參數(shù)也是用于指定函數(shù)體內 this 的指向,從第二個參數(shù)開始往后,每個參數(shù)被依次傳入被調用函數(shù)。
示例二:
function getInfo() { console.log(this.name+' like '+arguments[0]+' and '+arguments[1]);}var boy1 = { name: 'Bob', age: 12}getInfo.call(boy1,'sing','shopping'); //輸出Bob like sing and shopping此外,大部分高級瀏覽器還實現(xiàn)了 bind 方法,它與 call 和 apply 的區(qū)別在于 bind 只是改變函數(shù)內部 this 的指向,但不會立即執(zhí)行,你需要顯示調用它。
示例三:模擬瀏覽器的 bind 方法
Function.prototype.bind = function(obj){ var self = this; return function(){ return self.apply(obj,arguments); }};var obj = { name: 'Bob', age: 12};var func = function(){ console.log(this.name+' like '+arguments[0]+' and '+arguments[1]);}.bind(obj);func('sing','shopping');丟失的 this
在某些情況下會丟失 this 的指向,此時,我們就需要借助 call、apply 和 bind 來改變 this 的指向問題。
示例一:當 "getName" 方法作為 "boy" 對象的屬性調用時,this 指向 "boy" 對象,當另外一個變量引用 "getName" 方法時,因為它是作為普通函數(shù)調用,所以 this 指向全局對象window
var boy = { name: 'Bob', getName: function() { console.log(this.name); }}boy.getName(); //輸出Bobvar getBoyName = boy.getName;getBoyName(); //輸出undefined示例二:即使在函數(shù)內部定義的函數(shù),如果它作為普通對象調用,this 同樣指向 window 對象
var boy1 = { name: 'Bob', age: 12, getInfo: function() { console.log(this.name); function getAge() { console.log(this.age); } getAge(); }}boy1.getInfo(); //Bob //undefined新聞熱點
疑難解答