1. 程式人生 > >JavaScript中this指向

JavaScript中this指向

JavaScript中this的四大判定:

1.預設繫結this指向window:

example:

 function test (c){
            var a = 123;
            function b(){

            }
        }
        test(1);

在預編譯的過程當中

AO{ c:1 a:undefoned arguments:[1] this:window b:function(){} }

預設this指向window

舉個例子:

function test(){ console.log(this); } test();

打印出來的結果是:

在這裡插入圖片描述

而this的指向是: 在這裡插入圖片描述

所以預設this指向window

改變this指向有哪些方法

2.隱式的繫結:誰呼叫this指向誰

example:

var str = '11111';
    var obj = {
        str : '2222',
        callStr : function(){
            console.log(this.str);
        }
    }
    obj.callStr();// ---->列印的結果是2222,因為是obj呼叫this
var fun = obj.callStr;
 fun();// 列印的結果是11111,
// 因為var fun = obj.callStr;已經在全域性範圍內定義了fun,
 然後再呼叫fun,this就指向了window

3.顯示的轉換 call apply

4.new 操作符改變this指向

example:

var foo = '123';
function print(){
	this.foo = '789';
	console.log(foo);
}
 print();

打印出的結果是 789,預編譯環節,自己本身的AO裡面沒有foo,所以就去全域性GO裡面尋找,然後this指向window,所以GO中的foo = 123 就被 this中的foo取代為 789,

在new的情況下,

var foo = '123';
function print(){
	this.foo = '789';
	console.log(foo);
}
 new print();

打印出的結果是 123 建立new的時候,在函式內部裡面存在一個隱式的this

 var this = {
     
       __proto__ :Object.prototype  }

然後在預編譯的環節中,函式體裡面的AO物件中沒有foo,所以就會去全局裡面尋找,所以最後打印出的結果是123,new的權重最高。

總結: ESS this四大判定規則                              權重
      1.預設繫結this指向window                           預設
      2.隱式的繫結: 誰呼叫this指向誰                     ***
      3.顯示的轉換:  call apply                         ****
      4.new 操作符改變this指向                          *****