this初见

2017-08-03  本文已影响2人  pz明

一、概述

 this是JavaScript的一个关键字,它总是指向一个对象,不同的调用方式,this的值也有所不同。本文列举常见调用方式,指出相应情况下this指向的对象。

二、全局this

 JavaScript中,全局this直接指向window对象。

三、函数中this

 函数中的this具体指向的对象由函数的调用方式决定,主要有以下几种:
1.函数的直接调用,此时,this指向window对象

function fn(){
  console.log(this);
}
fn();//window

2.函数作为对象方法调用,此时,this指向当前对象

var obj={
  fn:function(){
    console.log(this)
  }
}
obj.fn()//obj

3.构造函数中的this,由new调用构造函数时,this指向新生成的对象

var People=function(){
  console.log(this);
}
var p=new People();//p

4.call,apply指定,此时,tihs就是指定的对象

function fn(){
  console.log(this);
}
var o={
  1:1
}
fn.call(o);//o

5.bind指定,注意:bind与call,apply的区别,bind并不直接调用函数,而是返回一个与原函数具有相同函数体和作用域的函数,返回函数的this被永久指定,无论如何调用此函数。

function fn(){
  console.log(this);
}
var o={
  1:1
}
var f2=fn.bind(o);
f2();//o
f2.call({2:2});//o

5.DOM事件处理函数中,this指向e.currentTarget,往往是添加监听的那个元素对象

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

1,this MDN
2,this 的值到底是什么?一次说清楚
3,Javascript的this用法

上一篇下一篇

猜你喜欢

热点阅读