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 #26

Open
incuisting opened this issue Sep 7, 2017 · 0 comments
Open

this #26

incuisting opened this issue Sep 7, 2017 · 0 comments

Comments

@incuisting
Copy link
Owner

先看一下这个例子:

var obj = {
  foo: function(){
    console.log(this)
  }
}

var bar = obj.foo
obj.foo() // 打印出的 this 是 obj
bar() // 打印出的 this 是 window

简单的解释就是:谁调用,this就指向谁。
obj.foo() 就是obj调用foo()
bar()打印出了window ,那么直接调用就是window直接调用bar()

但是谁调用,this就指向谁这个解释还是有点太片面。所以还有一个办法,就是把函数的调用转化为call()或者apply()调用的方式。
call()为例子

fn.call(context,p1,p2,p3.....)

这里的context 就是this
后面接的是传进去的参数
所以

bar()
//相当于
bar().call(undefined)

obj.foo()
//相当于
obj.foo().call(obj)

浏览器有一条规则:如果你传的 context 就 null 或者 undefined,那么 window 对象就是默认的 context(严格模式下默认 context 是 undefined)

this对象的指向是可变的,但是在ES6中箭头函数的this的指向是固定,绑定到定义时所在的作用域

function foo() {
  setTimeout(() => {
    console.log('id:', this.id);
  }, 100);
}

var id = 21;

foo.call({ id: 42 });
// id: 42

上面代码中,setTimeout的参数是一个箭头函数,这个箭头函数的定义生效是在foo函数生成时,而它的真正执行要等到100毫秒后。如果是普通函数,执行时this应该指向全局对象window,这时应该输出21。但是,箭头函数导致this总是指向函数定义生效时所在的对象(本例是{id: 42}),所以输出的是42。

参考文章:阮一峰es6

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