js中this指向

1.全局作用域或者普通函数中this指向全局对象window。

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

//自执行函数

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

2.方法调用中谁调用this指向谁

   //对象方法调用
    var person = {
        run: function () {console.log(this)}
    }
    person.run() // person
    
    //事件绑定
    var btn = document.querySelector("button")
    btn.onclick = function () {
        console.log(this) // btn
    }
    //事件监听
    var btn = document.querySelector("button")
    btn.addEventListener('click', function () {
       console.log(this) //btn
    })

    //jquery的ajax
     $.ajax({
        self: this,
        type:"get",
        url: url,
        async:true,
        success: function (res) {
            console.log(this) // this指向传入$.ajxa()中的对象
            console.log(self) // window
        }
       });

 //这里说明以下,将代码简写为$.ajax(obj) ,this指向obj,在obj中this指向window,因为在在success方法中,独享obj调用自己,所以this指向obj

3.在构造函数或者构造函数原型对象中this指向构造函数的实例

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

4.this可以被call和apply改变

js是动态语言,即拥有动态的数据类型,动态的函数执行和动态的方法执行,其中函数的动态执行的体现是eval,apply和call

call和apply的第一个参数为上下文的this,在this的改变上,两者没有区别

5.ES5中新增的bind和this

bind即为cal/apply的高级版,不过低版本的IE不支持,需要修复Function.prototype

var modal = {
  message: 'This is A'
}

function showMsg() {
  alert(this.message)
}

var otherShowMsg = showMsg.bind(modal)
otherShowMsg() // 'This is A'

6.ES6箭头函数(arrow function) 和 this

判断 this 指向谁,看执行时而非定义时,只要函数(function)没有绑定在对象上调用,它的 this 就是 window
是的,前面一直用这句话来判断 this 的指向,在箭头函数里前面半句就失效了。
箭头函数的特征就是,定义在哪,this 就指向那。即箭头函数定义在一个对象里,那箭头函数里的 this 就指向该对象。

var book = {
  author: 'John Resig',
  init: function() {
    document.onclick = ev => {
      alert(this.author) ; // 这里的 this 不是 document 了
    }
  }
};
book.init()

作者:codezha
来源:CSDN
原文:https://blog.csdn.net/codezha/article/details/76038553
版权声明:本文为博主原创文章,转载请附上博文链接!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值