this 的指向 以及 改變 this 指向的方法

2021-10-25 20:29:58 字數 1551 閱讀 8969

1、全域性作用域 或 普通函式 的呼叫 或 定時器函式 ,this 指向 window;

console.log(this);

function宣告函式

function fu()

fu(); //相當於 window.fu()

function宣告函式 賦值給變數

var fu = function ()

fu();

自執行函式

( function () )();

定時器函式

setinterval(function () , 1000);

2、方法呼叫中 誰 呼叫 this指向 誰

物件方法呼叫

var obj =

}obj.fu(

); //obj

事件繫結

var btn = document.queryselector(

"button"

)btn.onclick =

function()

//事件監聽

var btn = document.queryselector(

"button"

)btn.addeventlistener(

'click', function()

)//jquery的ajax

$.ajax(})

;

3、構造函式呼叫, 此時 this 指向 例項物件

function person(name,age)

person

} var p1 = new person(

"wanglei",18)

; var p2 = new person(

"hanmeimei",16)

;

4、箭頭函式中指向外層作用域的 this

var obj =

, bar: ()=

>

}obj.foo(

) //

obj.bar(

) // window

2、bind()

bind(thisscope, arg1, arg2, arg3…);

而bind 改變this的指向,返回的是函式

3、call()

call(thisscope, arg1, arg2, arg3…);

var myboy=}

var my =

"北京","三"])

;xw.say.bind(xh,"北京","三")(

);xw.say.bind(xh)

("北京","三");

xw.say.call(xh,"北京","三");

this 的指向以及如何改變指向

this 永遠指向最後呼叫它的那個物件 箭頭函式語法比函式表示式更短,並且不繫結自己的this需要通過查詢作用域鏈來確定 this 的值,如果箭頭函式被非箭頭函式包含,this 繫結的就是最近一層非箭頭函式的 this。在函式內部使用 this this 先將呼叫這個函式的物件儲存在變數 this ...

this指向 改變this指向

常見的this指向 常見的this指向 全域性下的this指向window 函式中的this,誰呼叫指向誰 建構函式中的this指向建構函式的物件 物件中的this預設指向當前物件 事件處理函式中this誰觸發指向誰 指向觸發事件的目標元素 定時器函式,this 指向 window 箭頭函式中沒有t...

this指向 改變this指向

function a a 此處相當於window.a 這僅是我個人的理解 在這個 中我們可以看出在 的結尾是由window來呼叫的函式a,那麼這個時候this指向window,this.user,全域性中沒有user,所以先定義了,但是沒有賦值,所以列印出undefined this指向練習二 va...