1.7 this关键字

JS中主要研究的都是函数中的this

JS中的this代表的是当前行为执行的主体;JS中的context代表的是当前行为执行的环境(区域);

this是谁和函数在哪定义的和在哪执行的都没有任何的关系:如何区分this呢?

  1. 函数执行,首先看函数名前面是否有“.”,有的话,“.”前面是谁this就是谁,没有的话this就是window

function fn () {
  console.log(this)
}
var obj = {fn:fn};
fn(); // this->window
obj.fn(); //this->obj
function sum () {
  fn(); // this->window
}
sum()
var oo = {
sum: function () {
  // this ->oo
fn(); // this->window
 }
}
oo.sum();

  2. 自执行函数中的this永远是window

  3. 给元素的某一个事件绑定方法,当事件触发的时候,执行对应得方法,方法中的this是当前的元素

<div id="div1"></div>
function fn () {
  console.log(this)
}
document.getElementById("div1").onclick = fn;// fn中的this是div1
document.getElementById("div1").onclick = function () {
// this -> #div1 fn();
//this ->window }

   4.在构造函数模式中,类中(函数体中)出现的this.xxx = xxx 中的this是当前类的一个实例

  5.call,applay,bind改变this指向(一但遇到call/apply上述的四条都没用了)

posted @ 2018-04-04 15:06  Z-DL  阅读(112)  评论(0编辑  收藏  举报