關於this在不同使用情況表示的含義
阿新 • • 發佈:2017-07-11
png tlist code targe his add window 作用 als
1. addEventListener 函數中的this 指向的是出發事件的事件源
obj.addEventListener(‘click‘,function(){ console.log(this);//this指向obj },false);
2.attachEvent 函數中的this 指向的是 window
obj.attachEvent(‘onclick‘,function(){ console.log(this);//this指向window });
//當如果需要使用attachEvent 中的事件源
obj.attachEvent(‘onclick‘,event => console.log(event.srcElement));
3.箭頭函數和普通函數內部的this 表示的意義(箭頭函數裏面根本沒有自己的this
,而是引用外層的this
。)
(如圖:普通函數指向的是widow 而箭頭函數指向的定義時所在的所用域 即 Timer)
除了this
,以下三個變量在箭頭函數之中也是不存在的,指向外層函數的對應變量:arguments
、super
、new.target
。
4. 大多數函數裏的this指向為當前作用域上一級的對象
是不是感覺第二種是個特例?
關於this在不同使用情況表示的含義