JavaScript 中的this

2017-07-26  本文已影响0人  shadow123

全局上下文

在全局运行上下文中,this指全局对象。

console.log(this.document === document); // true
console.log(this === window); //true

函数上下文

DOM事件处理函数中的 this

通常来说,this 的值是触发事件的元素的引用。

button.addEventListener('click',function(e){
    console.log(this === e.currentTarget); // true
})

jQuery 中的 this

当jQuery的调用处理程序时,this关键字指向的是当前正在执行事件的元素。对于直接事件而言,this 代表绑定事件的元素。对于代理事件而言,this 则代表了与 selector 相匹配的元素。

// HTML
<div class="div">
  <button>click me</button>
</div>
// CSS
.div{
    width:200px;
    height:200px;
    background:#3CA0D0;
    display:flex;
    justify-content:center;
    align-items:center;
}
// JS
$('div').on('click',function(e){
    console.log(this === e.currentTarget);
    console.log(this === e.target);
})

当点击button时,前一个是true ,后一个是false。当点击div时,都为true。
可以看出this就是 e.currentTarget。

call和apply

当一个函数的函数体中使用了this关键字时,通过所有函数都从Function对象的原型中继承的call()方法和apply()方法调用时,它的值可以绑定到一个指定的对象上。

简单说,this就是call和apply的第一个参数。

function add(c, d){
  return this.a + this.b + c + d;
}
var o = {a:1, b:3};
add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16
add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34

如何确定this

1.console.log(this)
2.看源代码
3.看API文档

看个例子

var name = 'jack';
var object = {
    name:'lucy',
    sayHi:function(){
        console.log('hi,' + this.name)
    }
}
var fn = object.sayHi;
fn(); // fn.call() //hi,jack
object.sayHi(); // obeject.sayHi.call(object)//hi,lucy
// HTML
<button name=btn>click me</button>
// JS
var button =document.querySelector('button');
var name = 'jack';
var object = {
    name:'lucy',
    sayHi:function(){
        button.onclick = this.onClick
    },
    onClick:function(){
        console.log(this.name)
    }
}
object.sayHi();

当button 点击时,this的指向是button,打印出来就是btn。

var button = document.querySelector('button');
var name = 'jack';
var object = {
    name: 'lucy',
    sayHi: function() {
        var that = this;
        button.onclick = function() {
            console.log(that.name);
        }
    },

}
object.sayHi();

此时,点击button,打印出来的就是lucy。

上一篇 下一篇

猜你喜欢

热点阅读