js中的this指向问题

情况1:如果一个函数中有this,但是它没有被上一级的对象所调用,那么this指向的就是window,这里需要说明的是在js的严格版中this指向的不是window,但是我们这里不探讨严格版的问题,你想了解可以自行上网查找。

情况2:如果一个函数中有this,这个函数有被上一级的对象所调用,那么this指向的就是上一级的对象。

情况3:如果一个函数中有this,这个函数中包含多个对象,尽管这个函数是被最外层的对象所调用,this指向的也只是该函数上一级的对象

var o = {

    a:10,

    b:{

        a:12,

        fn:function(){

            console.log(this.a); //12        }

    }

}

o.b.fn();

//b调用的fn 使用this指向b 即使嵌套多少 也是b调用的fn

函数如果是未调用方法获值 会指向window 如何在不调用时改变指向?call apply bind

var a = {

    user:"追梦子",

    fn:function(){

        console.log(this.user);

    }

}

var b = a.fn;

b(); //undefined

==> var b=a.fn;

   b.call(a);//b中的this指向a

彻底弄懂js中的this指向

总结了jsthis的常见用法,喜欢的可以看看:

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

})

//jqueryajax

 $.ajax({

    self: this,

    type:"get",

    url: url,

    async:true,

    success: function (res) {

        console.log(this) // this指向传入$.ajxa()中的对象

        console.log(self) // window

    }

   });

 //这里说明以下,将代码简写为$.ajaxobj) ,this指向obj,objthis指向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指向,将thiswindow指向Person的实例对象people

function getThis(){
  this.o = ‘1’;
}
 
1 直接调用函数 this指代是全局对象浏览器中即window对象
 getThis();
2 根据构造函数new一个新对象时this指代的是当前的new的对象
  varmyObj = new getThis();
3 call 与apply可以强制改变this的值
  call与apply里没有参数传入时采用默认值window,如果存在参数值则指向当前所传参的对象
4 addEvenetListener 与attachEvent
绑定事件时前者this指代的当前元素,而后者不管是哪种元素指代的都是window

猜你喜欢

转载自blog.csdn.net/weixin_39173093/article/details/80411869