理解this

151 阅读1分钟

this是call的第一个参数; 箭头函数没有this这个东西,所以箭头函数内外this不变

button.onclick = function(){
console.log(this)  //触发事件的元素:button
}
 
button.addEventListener ('click',function(){
console.log(this)  //该元素的引用
})

$('ul').on('click','li',function(){
console.log(this)  //this代表了与selector相匹配的元素,这里的selector就是li
})

要知道这时候onclick的this是什么,就去看mdn,onclick的第一个参数是什么

image.png
所以知道了是触发事件的元素即button。

第二个也一样,看addEventListener的mdn。

image.png

第三个也一样,看jQuery的文档。

image.png

button.onclick.call({name:'frank'}) this就是call的第一个参数,如果你没有看见call,你就不知道this是什么。 当你不写call的时候,就按照文档上的规则执行。

image.png
答案:打印出来是options

image.png
答案:打印出来是object、object

image.png
答案:打印出来是object

看懂这单个例子,对this就很理解了!