全局上下文
在全局运行上下文中,this指全局对象。
1 | console.log(this.document === document); // true |
2 | console.log(this === window); // true |
函数上下文
DOM事件处理函数中的 this
通常来说,this 的值是触发事件的元素的引用。
1 | button.addEventListener('click',function(e){ |
2 | console.log(this === e.currentTarget); // true |
3 | }) |
jQuery 中的 this
当jQuery的调用处理程序时,this关键字指向的是当前正在执行事件的元素。对于直接事件而言,this 代表绑定事件的元素。对于代理事件而言,this 则代表了与 selector 相匹配的元素。
1 | // HTML |
2 | <div class="div"> |
3 | <button>click me</button> |
4 | </div> |
5 | // CSS |
6 | .div{ |
7 | width:200px; |
8 | height:200px; |
9 | background:#3CA0D0; |
10 | display:flex; |
11 | justify-content:center; |
12 | align-items:center; |
13 | } |
14 | // JS |
15 | $('div').on('click',function(e){ |
16 | console.log(this === e.currentTarget); |
17 | console.log(this === e.target); |
18 | }) |
当点击button时,前一个是true ,后一个是false。当点击div时,都为true。
可以看出this就是 e.currentTarget。
call和apply 方法
当一个函数的函数体中使用了this关键字时,通过所有函数都从Function对象的原型中继承的call()方法和apply()方法调用时,它的值可以绑定到一个指定的对象上。
简单说,this就是call和apply的第一个参数。
1 | function add(c, d){ |
2 | return this.a + this.b + c + d; |
3 | } |
4 | var o = {a:1, b:3}; |
5 | add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16 |
6 | add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34 |
如何确定this
1.console.log(this)
2.看源代码
3.看API文档
看个例子
1 | var name = 'jack'; |
2 | var object = { |
3 | name:'lucy', |
4 | sayHi:function(){ |
5 | console.log('hi,' + this.name) |
6 | } |
7 | } |
8 | var fn = object.sayHi; |
9 | fn(); // fn.call() //hi,jack |
10 | object.sayHi(); // obeject.sayHi.call(object)//hi,lucy |
1 | // HTML |
2 | <button name=btn>click me</button> |
3 | // JS |
4 | var button = document.querySelector('button'); |
5 | var name = 'jack'; |
6 | var object = { |
7 | name: 'lucy', |
8 | sayHi: function() { |
9 | button.onclick = this.onClick |
10 | }, |
11 | onClick: function() { |
12 | console.log(this.name); |
13 | } |
14 | } |
15 | |
16 | object.sayHi(); |
当button 点击时,this的指向是button,打印出来就是btn。
1 | var button = document.querySelector('button'); |
2 | var name = 'jack'; |
3 | var object = { |
4 | name: 'lucy', |
5 | sayHi: function() { |
6 | var that = this; |
7 | button.onclick = function() { |
8 | console.log(that.name); |
9 | } |
10 | }, |
11 | |
12 | } |
13 | object.sayHi(); |
此时,点击button,打印出来的就是lucy。