首先,我们来了解一下 this 的几种绑定方式:

  this的默认绑定:

 当一个函数没有明确的调用对象的时候,即作为独立函数调用时,this绑定到全局window对象。

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

  this的隐式绑定:

 当函数被其他对象包含再其中时,这时this被隐式绑定到了这个对象中;因此,通过this可以直接访问到该对象中的其他属性。

var foo = {name:'Lily'}
var obj = {
name: 'John',
age: 20,
sayName: function(){
console.log(this === obj);
console.log(this.name);
}
}
obj.sayName(); //true John
foo.sayName = obj.sayName;
foo.sayName(); //false Lily

  this的显式绑定:

 调用call() 或 apply()方法来实现this的主动绑定

var animals = [
{species: 'Lion', name: 'King'},
{species: 'Whale', name: 'Fail'}
]; for (var i = 0; i < animals.length; i++) {
(function (i) {
this.print = function () {
console.log('#' + i + ' ' + this.species + ': ' + this.name);
}
this.print();
}).call(animals[i], i);
}
//#0 Lion: King
//#1 Whale: Fail

  this的new绑定:

 函数被执行new操作后,将创建一个新的对象,并将构造函数的this指向所创建的构造函数。

function foo(name){
this.name = name
} var bar = new foo('John');
console.log(bar.name); //John

  this的硬绑定

 当this被强制绑定后,无论之后任何调用该this都不变

var a = 5;
function foo(){
console.log(this.a);
}
var obj = {
a: 2
}
var bar = function(){
foo.call(obj);
}
bar(); //
bar.call(window);//

  

说完上述几种this绑定的情况后,就要来说一下箭头函数中的this了:

  

function foo() {
return () => {
return () => {
console.log(this)
}
}
}
console.log(foo()()()) //window

  箭头函数中实际上并没有this箭头函数中的this只取决包裹箭头函数的第一个普通函数的this。在这个例子中,因为包裹箭头函数的第一个普通函数是foo,所以此时的this是window。

  

随机推荐

  1. Sitemap Error : XML declaration allowed only at the start of the document解决方法

    今天ytkah的客户反馈说他的xml网站地图有问题,提示Sitemap Error : XML declaration allowed only at the start of the documen ...

  2. 解决node.js链接数据库时出现的报错 --- client does not support authentication

    打开mysql数据库小黑屏 然后输入 mysql> alter user 'root'@'localhost' identified with mysql_native_password by ...

  3. Codeforces 1038 D. Slime

    [传送门] 其实就是这些数字前面能加正负号,在满足正负号均出现的情况下价值最大.那么就可以无脑DP$f[i][j][k]$表示到了第$i$位,正号是否出现($j$.$k$为$0$或$1$)能得到的最大 ...

  4. 开发(二) ardunio批量固件上传地址

    https://blog.csdn.net/Naisu_kun/article/details/84958561 批量烧录固件到模块中上面讲了如何编写上传程序,接下来讲讲如何量产.相比<Ardu ...

  5. BZOJ 1818: [Cqoi2010]内部白点 扫描线+树状数组

    问题转化为求每一个极长横线段与极长纵线段的交点个数. 这个东西用扫描线+树状数组维护一下就可以了. code: #include <cstdio> #include <algorit ...

  6. 同余and乘法逆元学习笔记

    目录 数学符号 快速幂 方法一 方法二 同余 概念 同余的性质 乘法逆元 概念: 求逆元的方法 扩展欧几里得 快速幂法\(o(n*log(n))\) 递推法\(o(n)\) sjp大佬让我写同余那就只 ...

  7. 你真的知道Java中boolean类型占用多少个字节吗?

    为什么要问这个问题,首先在Java中定义的八种基本数据类型中,除了其它七种类型都有明确的内存占用字节数外,就boolean类型没有给出具体的占用字节数,因为对虚拟机来说根本就不存在 boolean 这 ...

  8. 模拟25A 题解

    A. Lighthouse m的范围极小,显然的容斥. 总的方案数,减去受任意一个限制的方案数,加回受两个限制的方案数. 就能得到受所有限制的的方案数. 将选择的一些边所指向的点放在同一个联通块里. ...

  9. [Beta阶段]第五次Scrum Meeting

    Scrum Meeting博客目录 [Beta阶段]第五次Scrum Meeting 基本信息 名称 时间 地点 时长 第五次Scrum Meeting 19/05/10 新主楼F座2楼 50min ...

  10. 记一次 HttpClient 死锁问题

    原文:http://blog.kail.xyz/post/2019-04-21/tools/httpclient-lock.html 最近遇到一个使用 Apache HttpClient 过程中的问题 ...