zoukankan      html  css  js  c++  java
  • 你不知道的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()();         
  • 相关阅读:
    LINUX安装NGINX
    CentOS 设置mysql的远程访问
    centos6 mysql 安装与配置
    php读取用友u8采购入库单列表及详细
    php读取用友u8客户档案
    深度linux没有ll等命令的解决办法
    CentOS7下FTP的安装与配置
    虚拟机CentOS6.5搭建samba服务器实现文件共享
    linux 查找php.ini在那个文件夹
    CBE引擎概览
  • 原文地址:https://www.cnblogs.com/linxianzuo/p/6244009.html
Copyright © 2011-2022 走看看