We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
this 不是在编写时候绑定的,而是在运行时候绑定的上下文执行环境。this 绑定和函数申明无关,反而和函数被调用的方式有关系。
当一个函数被调用的时候,会建立一个活动记录,也成为执行环境。这个记录包含函数是从何处(call-stack)被调用的,函数是 如何 被调用的,被传递了什么参数等信息。这个记录的属性之一,就是在函数执行期间将被使用的 this 引用。
this 默认绑定
this
严格模式下,this 绑定到 underfined,否则绑定到全局对象。
underfined
this 隐式绑定
函数中的 this 是多变的,但是规则是不变的。一般情况下,this不是在编译的时候决定的,而是在运行的时候绑定的上下文执行环境。this 与声明无关。
隐式丢失其实就是被隐式绑定的函数在特定的情况下会丢失绑定对象。
有两种情况容易发生隐式丢失问题:
如果把一个函数当成参数传递到另一个函数的时候,也会发生隐式丢失的问题,且与包裹着它的函数的 this 指向无关。在非严格模式下,会把该函数的 this 绑定到 window 上,严格模式下绑定到 undefined。
window
undefined
this 绑定的是新创建的对象
类通常包含一个 constructor , this 可以指向任何新创建的对象。
constructor
强绑定,显示绑定,直接更改 this 的指向
.call()
.apply()
bind()
call
apply
bind
null
forEach
map
filter
优先级:new绑定 > 显式绑定 > 隐式绑定 > 默认绑定
箭头函数中没有 this 绑定,必须通过查找作用域链来决定其值,如果箭头函数被非箭头函数包含,则 this 绑定的是最近一层非箭头函数的 this,否则,this 为 undefined。
此外,使用 call 、 apply 或 bind 等方法给 this 传值,箭头函数会忽略。箭头函数引用的是箭头函数在创建时设置的 this 值。
一般指向绑定事件的 DOM 元素,但有些情况绑定到全局对象,比如 IE6-8 的 attachEvent。 例如:
attachEvent
document.body.addEventListener('click', fn, false); function fn(e) { console.log(this === e.currentTarget); }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
什么是this
this 不是在编写时候绑定的,而是在运行时候绑定的上下文执行环境。this 绑定和函数申明无关,反而和函数被调用的方式有关系。
当一个函数被调用的时候,会建立一个活动记录,也成为执行环境。这个记录包含函数是从何处(call-stack)被调用的,函数是 如何 被调用的,被传递了什么参数等信息。这个记录的属性之一,就是在函数执行期间将被使用的 this 引用。
四种绑定方式
函数调用
严格模式下,
this
绑定到underfined
,否则绑定到全局对象。方法调用
当一个函数被调用的时候,会建立一个活动记录,也成为执行环境。这个记录包含函数是从何处(call-stack)被调用的,函数是 如何 被调用的,被传递了什么参数等信息。这个记录的属性之一,就是在函数执行期间将被使用的
this
引用。函数中的
this
是多变的,但是规则是不变的。一般情况下,this不是在编译的时候决定的,而是在运行的时候绑定的上下文执行环境。this
与声明无关。隐式绑定丢失
隐式丢失其实就是被隐式绑定的函数在特定的情况下会丢失绑定对象。
有两种情况容易发生隐式丢失问题:
this
绑定如果把一个函数当成参数传递到另一个函数的时候,也会发生隐式丢失的问题,且与包裹着它的函数的
this
指向无关。在非严格模式下,会把该函数的this
绑定到window
上,严格模式下绑定到undefined
。构造函数调用
类通常包含一个
constructor
,this
可以指向任何新创建的对象。间接调用
this
永远指向最后调用它的那个对象this
永远指向window
.call()
或者.apply()
的函数是会直接执行的bind()
是创建一个新的函数,需要手动调用才会执行call
、apply
、bind
接收到的第一个参数是空或者null
、undefined
的话,则会忽略这个参数forEach
、map
、filter
函数的第二个参数也是能显式绑定this
的箭头函数
箭头函数中没有
this
绑定,必须通过查找作用域链来决定其值,如果箭头函数被非箭头函数包含,则this
绑定的是最近一层非箭头函数的this
,否则,this
为undefined
。此外,使用
call
、apply
或bind
等方法给this
传值,箭头函数会忽略。箭头函数引用的是箭头函数在创建时设置的this
值。一些特殊情况下的
this
DOM �事件函数
一般指向绑定事件的 DOM 元素,但有些情况绑定到全局对象,比如 IE6-8 的
attachEvent
。例如:
参考资料
The text was updated successfully, but these errors were encountered: