• 你不知道的this指向


    javascript中,我们预想的this指向,有时候与预期不一样,直接上经典例子

        window.name=2;
        var test={
                'name':1,
                'getName':function(){
              console.log(this.name);//输出1
                 return function(){
                   console.log(this.name);//输出2
                    }
                }
            }
        
        test.getName()();         

      上面为最经典的一个this指向解析案例,第一个this指向test对象,第二个this指向window全局对象,第一个console运行的是test对象里面的方法 ,第二个console运行的是一个匿名函数(也可以称为普通函数)在JavaScript中普通函数的this指向的是全局对象的,上面字面量的创建test对象隐含着new关键词,整个test是一个新的对象,getName属于test里面的方法,this会指向test对象,而getName里面return的函数,属于一个普通函数,这个函数里的this会指向window全局,

    ps:其实还可以用闭包的解析,我个人觉得如果这个没弄明白,再提闭包会让人更加迷惘。

    假设你想把第二对象指向test,可以使用call在调用时候改变

          window.name=2;
        var test={
                'name':1,
                'getName':function(){
                      console.log(this.name);
                    return function(){
                        console.log(this.name);
                    }
                }
            }
        
        test.getName().call(test); //输出1,1    
        test.getName().apply(test); //输出1,1 

    还有一个改变this对象的方法,在test里面的方法嵌套函数之前,先把test对象(指向test的this)用变量的方式保存下来,下面的案例代码

          window.name=2;
        var test={
                'name':1,
                'getName':function(){
                    var that=this;//预先把指向test的this保存到that变量中
                 console.log(this.name);//输出1
                    return function(){
                        console.log(that.name);//输出1
                    }
                }
            }
        
        test.getName()();         
  • 相关阅读:
    govalidators 验证
    go iris框架 获取url的两种方法
    tornado框架
    并发/并行,阻塞/非阻塞,同步/异步
    CSS选择器及优先级
    linux下压力测试命令ab
    asyncio
    linux网络原理及基础设置
    linux命令
    linux简介
  • 原文地址:https://www.cnblogs.com/linxianzuo/p/6244009.html
Copyright © 2020-2023  润新知