Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript 中的 this #13

Closed
Tracked by #6
swiftwind0405 opened this issue Feb 27, 2020 · 0 comments
Closed
Tracked by #6

JavaScript 中的 this #13

swiftwind0405 opened this issue Feb 27, 2020 · 0 comments

Comments

@swiftwind0405
Copy link
Owner

swiftwind0405 commented Feb 27, 2020

image


什么是this

this 不是在编写时候绑定的,而是在运行时候绑定的上下文执行环境。this 绑定和函数申明无关,反而和函数被调用的方式有关系。

当一个函数被调用的时候,会建立一个活动记录,也成为执行环境。这个记录包含函数是从何处(call-stack)被调用的,函数是 如何 被调用的,被传递了什么参数等信息。这个记录的属性之一,就是在函数执行期间将被使用的 this 引用。

四种绑定方式

函数调用

this 默认绑定

严格模式下,this 绑定到 underfined,否则绑定到全局对象。

方法调用

this 隐式绑定

当一个函数被调用的时候,会建立一个活动记录,也成为执行环境。这个记录包含函数是从何处(call-stack)被调用的,函数是 如何 被调用的,被传递了什么参数等信息。这个记录的属性之一,就是在函数执行期间将被使用的 this 引用。

函数中的 this 是多变的,但是规则是不变的。一般情况下,this不是在编译的时候决定的,而是在运行的时候绑定的上下文执行环境this 与声明无关。

隐式绑定丢失

隐式丢失其实就是被隐式绑定的函数在特定的情况下会丢失绑定对象。

有两种情况容易发生隐式丢失问题:

  • 使用另一个变量来给函数取别名
  • 将函数作为参数传递时会被隐式赋值,回调函数丢失 this 绑定

如果把一个函数当成参数传递到另一个函数的时候,也会发生隐式丢失的问题,且与包裹着它的函数的 this 指向无关。在非严格模式下,会把该函数的 this 绑定到 window 上,严格模式下绑定到 undefined

构造函数调用

this 绑定的是新创建的对象

类通常包含一个 constructorthis 可以指向任何新创建的对象。

间接调用

强绑定,显示绑定,直接更改 this 的指向

  • this 永远指向最后调用它的那个对象
  • 匿名函数的 this 永远指向 window
  • 使用 .call() 或者 .apply() 的函数是会直接执行的
  • bind() 是创建一个新的函数,需要手动调用才会执行
  • 如果 callapplybind 接收到的第一个参数是空或者 nullundefined 的话,则会忽略这个参数
  • forEachmapfilter 函数的第二个参数也是能显式绑定 this

优先级:new绑定 > 显式绑定 > 隐式绑定 > 默认绑定

箭头函数

箭头函数中没有 this 绑定,必须通过查找作用域链来决定其值,如果箭头函数被非箭头函数包含,则 this 绑定的是最近一层非箭头函数的 this,否则,thisundefined

此外,使用 callapplybind 等方法给 this 传值,箭头函数会忽略。箭头函数引用的是箭头函数在创建时设置的 this 值。

一些特殊情况下的this

DOM �事件函数

一般指向绑定事件的 DOM 元素,但有些情况绑定到全局对象,比如 IE6-8 的 attachEvent
例如:

document.body.addEventListener('click', fn, false);

function fn(e) {
	console.log(this === e.currentTarget);
}

参考资料

@swiftwind0405 swiftwind0405 changed the title 【day06】this 【Day05】this Feb 27, 2020
@swiftwind0405 swiftwind0405 changed the title 【Day05】this 【JavaScript】this Apr 29, 2020
@swiftwind0405 swiftwind0405 changed the title 【JavaScript】this JavaScript 中的 this Oct 20, 2020
This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant