this 指向


关于JS中的THIS的基本情况分析

1.事件绑定
 DOM0: xxx.onxxx=function(){}
 DOM2: xxx.addEventListener('xxx',function(){})
     xxx.attachEvent('onxxx',function(){})
  给当前元素的某个事件行为绑定方法「此时是创建方法,方法没执行」,当事件行为触发,
 浏览器会把绑定的函数执行,此时函数中的this -> 当前元素对象本身
 document.body.addEventListener('click', function(){
    console.log(this);  //->body
  })
  特殊:基于attachEvent实现事件绑定,方法执行,方法中的this是window

  
2.函数执行「普通函数执行、成员访问、匿名函数、回调函数...」
 正常的普通函数执行:看函数执行前是否有“点”,有“点”前面是谁this就是谁,没有“点”,
 this是window「严格模式下是undefined」
    function fn() {
     console.log(this);
     }
     let obj = {
     name: 'xiaoming',
        fn
     }
    fn();  //this->window/undefined
    
    obj.fn();  //this->obj
   
     (10, obj.fn)();  //this->window/undefined

匿名函数:

    + 函数表达式:等同于普通函数或者事件绑定等机制
+ 自执行函数:this一般都是window/undefined
+ 回调函数:一般都是window/undefined,但是如果另外函数执行中,对回调函数的执行
    做了特殊处理,以自己处理的为主

    
(function(x) {
  console.log(this);  //->window/undefined
})(10);   
  let arr = [10,20,30]; arr.forEach(function(item, index) {     console.log(this)  //->window });
arr.forEach(function(item, index) {   console.log(this)  //->forEach第二个参数「对象」,forEach内部做处理了 },{xxx: 'xxx'});
setTimeout(function(x){   console.log(this, x);  //->window 10 }, 1000, 10);

    括号表达式:小括号中包含“多项”,这样也只取最后一项,但是this受到影响(一般是window/undefined)


3.构造函数「构造函数中的this指向它的实例对象」

4.箭头函数「箭头函数中的this指向是捕获它本身所在上下文中的this」

5.基于call/apply/bind强制修改this指向

...

最后我们来看一道题
 var x = 3,
     obj = {
       x:5
     };
 obj.fn = (function(){
     this.x *= ++x;
     return function(y){
        this.x *= (++x)+y;
        console.log(x);
     }
  })();    
   var fn = obj.fn;
   obj.fn(6); //13
   fn(4); //234
   console.log(obj.x, x);  // 95 234

 

欢迎您的观光,洗耳恭听您的宝贵意见!

 

posted @ 2022-04-10 21:54  无处安放的code  阅读(56)  评论(0)    收藏  举报