js 函数中this指向谁

2019-06-12  本文已影响0人  希染丶

一句话总结

谁调用函数,this就指向谁

注意点

1.this指向的,永远是对象
2.this指向谁, 不取决与this写在哪,而是取决于函数在哪调用
3.this指向的对象,我们成为函数的上下文context,也叫函数的调用者

具体情况

1.通过函数名()直接调用:指向window

funciton fn(){
  console.log(this)
}
fn()
输出: window对象

2.通过对象.函数名()调用:指向这个对象

var obj = {
  log: function (){
    console.log(this)
  }
}
obj.log();
输出:obj

3.通过数组下标.函数名()调用,指向这个数组

var arr = [];
function a(){
  console.log(this)
}
arr.push(a)
arr[0]()
输出: arr

4.通过window内置函数( setInterval setTimeout 等)的回调里调用。指向window

function fn(){
  console.log(this)
}
setTimeout(fn,1000);
输出: window

5.函数作为构造函数,new关键字实例化之后调用,指向实例化对象

function a(){
  this.log = function (){
    console.log(this)
  }
}
funciton b(){

}
b.prototype = new a();
var c = new fn2()
上一篇 下一篇

猜你喜欢

热点阅读