4

js this 绑定和箭头函数定义

 3 years ago
source link: https://www.v2ex.com/t/795138
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

定义:箭头函数相当于匿名函数,并且简化了函数定义

如:x => x * x

1.箭头函数看上去是匿名函数的一种简写,但实际上,箭头函数和匿名函数有个明显的区别:箭头函数内部的 this 是词法作用域,由上下文确定。

2.箭头函数的 this 指向取决于外层作用域中的 this,外层作用域或函数的 this 指向谁,箭头函数中的 this 便指向谁

来源:https://www.liaoxuefeng.com/wiki/1022910821149312/1031549578462080

this 绑定

1.this 默认绑定:我们可以理解为函数调用时无任何调用前缀的情景,默认绑定时 this 指向全局对象(非严格模式)

2.隐式绑定:如果函数调用时,前面存在调用它的对象,那么 this 就会隐式绑定到这个对象上,如果函数调用前存在多个对象,this 指向距离调用自己最近的对象

3.显示绑定:通过 call 、apply 以及 bind 方法改变 this 的行为,相比隐式绑定,我们能清楚的感知 this 指向变化过程,如果在使用 call 之类的方法改变 this 指向时,指向参数提供的是 null 或者 undefined,那么 this 将指向全局对象

4.new 绑定:抽象理解为新对象就是 this

5.this 绑定优先级:显式绑定 > 隐式绑定 > 默认绑定,new 绑定 > 隐式绑定 > 默认绑定 ,不存在同时显示和 new 绑定同时生效的场景

来源:https://www.cnblogs.com/echolun/p/11962610.html


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK