zoukankan      html  css  js  c++  java
  • js--call、箭头函数/匿名函数

    js中的this指向(较简单的几种):

    1.普通函数的this指向window;

    2对象方法指向当前对象;

    3.()=》箭头函数指向定义时的对象;

    apply和call可以改变当前的this指向,但是不能改变箭头函数的指向

    function foo() {
      return () => {
        return () => {
          return () => {
            console.log('id:', this.id);
          };
        };
      };
    }
    
    var f = foo.call({id: 1});
    
    var t1 = f.call({id: 2})()(); // id: 1
    var t2 = f().call({id: 3})(); // id: 1
    var t3 = f()().call({id: 4}); // id: 1

    上面举了个例子,说明箭头函数的this是不能改变的,相反,如果是普通匿名函数,就可以改变:

    function foo() {
      return () => {
        function() {
            console.log('id:', this.id);
        };
      };
    }
    
    var f1 = foo.call({id: 1})()()//undefined;
    var f2 = foo().call({id: 1})()//undefined;
    var f3 = foo()().call({id: 1})//1

    前两个this最后指向了window,最后一个指向{ID:1}

  • 相关阅读:
    (一)ngxin默认虚拟主机
    centos7 搭建LNMP
    centos7 搭建安装zabbix3.0邮件告警实例(二)
    Java BitSet(位集)
    OLTP与OLAP的区别
    Cassandra-LSM树
    LSM树
    Docker
    RESTful API
    kubernetes介绍
  • 原文地址:https://www.cnblogs.com/walei/p/7132547.html
Copyright © 2011-2022 走看看