zoukankan      html  css  js  c++  java
  • this

    this

    指向当前对象。

    各种情况

    全局上下文

    node.js对全局上下文this特殊处理。

    console.log(this); ——输出 {}

    this 全局上下文和函数指向 全局

    函数

     var func=function(){
            console.log(this);
        }
        func();            // 全局

    对象

    • 只有对象.方法,this指向当前对象;其余都是指向全局。
    • 在对象的方法使用this,指向当前对象
    • 在对象方法里嵌套,普通函数的调用,指向全局

      var stu=(){
          name:'ww',
          intro:function(){
              console.log(this,this.name);
          }
      }
      stu.intro(); 

    改变this的指向方法

    call , apply

    执行函数,并改变this指向

    区别:

    • call:以参数列表形式传递;
    • apply:以数组传递

      var func=function(a,b){
          console.log(this);
          console.log('hello',a,b);
      }
      func.call(11,22);
      func.call('hello',[11,22]);

    bind

    声明函数,在函数后面{}末尾。

    函数声明时,利用 bind 改变this指向。

    箭头函数 =>

    箭头函数中的this和上下文的this一致。

    内部没有作用范围(上下文),this指向和外部一样。

    var func1 = a => (++a); ()表示有return.
    7var myObject={
            foo:'bar',
            func:function(){
                var self=this;
                console.log(this.foo);  // bar;
                console.log(self.foo); //  bar;   self=this
                (function(){ // 嵌套,指向全局
                    console.log(this.foo);  // undefined; 未定义,在整个(var myObject)外部找,没有foo
                    console.log(self.foo); // bar; 找的上一个console.log(self.foo);输出的值
                })()
            }
        }
        myObject.func();
    8var User={
            count:1,
            getCount:function(){
                return this.count;  // 1,renturn返回值
            }
        }
        console.log(User.getCount()); // 1;
    
        var func=User.getCount;
        console.log(func());  // undefined;

     全局上下文和函数 this 指向全局;只有对象.方法,this指向当前对象,其余指向全局。

      call/aplly都可执行函数,但传参不同;bind声明函数在函数后面{}末尾;箭头函数=> .

  • 相关阅读:
    2019-9-2-正则表达式30分钟入门教程
    2019-6-23-开源项目使用-appveyor-自动构建
    2019-8-29-dotnet-core-使用-sqlite-部署到-Centos-服务器
    2018-10-19-Roslyn-使用-Directory.Build.props-文件定义编译
    2019-4-29-dotnet-通过-WMI-获取系统安装软件
    2018-12-24-win10-uwp-求两个矩形相连的几何
    shell公共函数functions
    linux防火墙和SELinux
    ubuntu开启ssh
    文件夹操作
  • 原文地址:https://www.cnblogs.com/llying/p/7658950.html
Copyright © 2011-2022 走看看