彻底理解javascript中this指向大全

在学习javascript过程中,难免会遇到this指向问题而掉入很多坑,以下就谈谈学习过程中遇到的this指向问题进行归类总结,希望可以帮到更多同学弃坑,哈哈。

一、全局作用域或者纯函数中this指向全局对象window。

//在脚本直接打印
console.log(this) //window

//function声明函数
function foo () {console.log(this)}
foo() //window

//function声明函数赋给变量
var bar = function () {console.log(this)}
bar() //window

//立即执行函数
(function () {console.log(this)})(); //window

//在setTimeout或setInterval 中
setTimeout(function(){
    console.log(this); //window
}, 1000)
setInterval(function(){
    console.log(this); //window
}, 1000)

二、谁调用了方法this指向谁

//对象方法调用
var person = {
    name: "老王",
    fighting: function () {console.log(this)}
}
person.fighting() // person

//事件绑定
var oBox = document.getElementById("box")
oBox.onclick = function () {
    console.log(this) // oBox
}

//事件监听
var oBox = document.getElementById("box")
oBox.addEventListener('click', function () {
   console.log(this) //oBox
})

三、在构造函数中this指向构造函数的实例

//使用new
function Person (name) {
      this.name = name;
      console.log(this); //people
  }
var people = new Person('老王')
//这里new改变了this指向,将this由window指向Person的实例对象people

四、call/apply中this指向绑定的对象

//this指向绑定的对象,即call或apply括号里的对象
var name = 'this is window'; //定义window的name属性,看this.name是否会调用到 
var person1 = { 
 name : 'this is 老赵', 
 getName:function(){ 
 console.log(this); //person2 
 console.log(this.name); //this is 隔壁老王
 } 
}
var person2 = { 
 name: 'this is 隔壁老王'
}
testObj1.getName.apply(person2); 
testObj1.getName.call(person2);

希望可以帮到大家,希望掉坑的同学可以早日脱离苦海,哈哈哈。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值