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

this #14

Open
zhangyanan0525 opened this issue Aug 10, 2018 · 0 comments
Open

this #14

zhangyanan0525 opened this issue Aug 10, 2018 · 0 comments

Comments

@zhangyanan0525
Copy link
Owner

zhangyanan0525 commented Aug 10, 2018

this

资料来自《你不知道的js上》这篇其实是学习笔记

this到底是什么

this 是在函数运行时进行绑定的,并不是在编写时绑定,它的上下文取决于函数调 用时的各种条件。this 的绑定和函数声明的位置没有任何关系,只取决于函数的调用方式。

按照以下优先级来判断this

  1. 函数是否在new中调用(new绑定)?如果是的话this绑定的是新创建的对象。
    var bar = new foo()
  2. 函数是否通过call、apply(显式绑定)或者硬绑定调用?如果是的话,this绑定的是 指定的对象。
    var bar = foo.call(obj2)
  3. 函数是否在某个上下文对象中调用(隐式绑定)?如果是的话,this 绑定的是那个上 下文对象。
    var bar = obj1.foo()
  4. 如果都不是的话,使用默认绑定。如果在严格模式下,就绑定到undefined,否则绑定到 全局对象。
    var bar = foo()
  5. 箭头函数会继承外层函数调用的 this 绑定(无论 this 绑定到什么)

有趣的小栗子

function foo() { 
    console.log( this.a );
}
var obj = { 
    a: 2,
    foo: foo
 };
var a = "oops, global";     // a 是全局对象的属性 
setTimeout( obj.foo, 100 );     // "oops, global"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant