function this的指向性问题

一,传统函数中的this指向

方法由谁调用,this指向的就是谁

1,在全局中定义的函数,this指向window
 

 var name = "mickey "; //全局变量name是window. name
        function person() {
            this.name= "tom";这里改了之后,上面定义的全局变量name随之改变
            console.log(this); //指向window
            console.log(this.name); //当使用对象方法时,指向的是对象
        }
        普通函数调用
        person(); //指向与window


2,对象方法中的this指向这个对象
      当作某个对象的方法
     

  var name = "tom";
        var person = {
            name: "tom",
            showName: function() {
                console.log(this.name);
            }
        }
        person.showName() //tom  this指向person


3、构造函数创建对象的方法中的this指向new出来的对象
     

var name = "mickey";
 
function Person(name) {
            this.name = name;
            this.showName = function() {
                console.log(this.name)
                console.log(this)
            }
        }
        var p = new Person("tom");
        p.showName();


4、定时器的this—指向window对象

 var name = "mickey";
 
        function Person(name) {
            this.name = name;
            this.showName = function() {
                // console.log(this.name);
                setTimeout(function() {
                    console.log(this.name); //mikey
                    console.log(this); //window
                }, 1000)
            }
        }
        var p = new Person("tom");
        p.showName(); //"tom"


 二,箭头函数中的this指向
        箭头函数体内的this对象就是定义时所在的对象,而不是使用时所在的对象。

        简单而言,箭头函数使用时,不绑定this对象,箭头函数没有自己的this,它的this是继承而来的,默认指向在定义箭头函数时所处的对象。

     

function f() {
  return () => {
    return () => {
      return () => {
        console.log('id:', this.id);
      };
    };
  };
}
var f = f.call({id: 1});        // 设置f的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,就是函数f的this。所以t1、t2、t3都输出同样的结果。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值