this 随笔

(1)普通函数申明

function t(){
	console.log(this)
}
t();//window
var tt={};
tt.x=t;
tt.x();//tt  this指向当前调用对象

function tt(){ 
	return function(){ console.log(this)}
}
tt()(); //window

function t(t=function(){console.log(this)}){t()}
t(); //window

(2)箭头函数

var t=()=>{console.log(this)}
t();//window;
var tt={};
tt.x=t;
tt.x();//window 箭头函数 this指向当前作用域

var t={x:()=>{console.log(this)},y:function(){ console.log(this)}}
t.x();//window  因为箭头函数本身没有this 他的this指向当前作用域, 而创建obj的时候并无作用域,所以指向 window
t.y();// t   普通方法的this是延迟绑定的,指向当前调用对象,
t.y.call(null);  t.y.call(window);  // 都是window

var t={x:function(call){call()}}
t.x(()=>{console.log(this)})// window  箭头函数它并不延迟绑定,指向的作用域依旧是window

继续:
var t={ x: function(){  return ()=>{console.log(this)}   } }
var tt={y:1}
t.x.call(tt);  //  this == tt ,  why?   x是普通函数,  他的this指向tt ,  x返回的箭头函数寻找外层作用域中的this 找到的是 x 的作用域,也就是tt的 this 

es6中的一个例子:
function foo() {
  return () => {
    return () => {
      return () => {
        console.log(this);
      };
    };
  };
}
foo()()()();//window
var t=new foo();
t()()();//foo

(3)类

class T{
	t(){
		console.log(this);
	};
}
var t=new T();
t.t();//T

由于this的延迟绑定, 所以方法或函数执行时才会绑定this,所以我理解的是:如果call 、apply 到null 上面,等同于全局作用域中申明函数一样,this 指向window。

function t(){ console.log(this)}
t.call(null);
// this== window

var t={ tt:function(){console.log(this)}}
t.tt.call(null);
//this ==window

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值