this 的指向,apply、bind、call 一起搞定~
this
this 是在执行函数时,创建的上下文对象中的一个属性,它允许在调用函数时决定哪个对象是焦点。所以 this
一般是在函数执行时确定的。
this 指向的是谁
一般情况下,请记住 "谁调用我,我就代表谁"。
谁调用这个函数,函数中的 this 就指向谁。var name = 'window'function foo() { var name = 'foo' console.log(this.name)}foo() // 'window'复制代码
执行 foo()
相当于执行 window.foo()
(非严格模式) 也就是 window
调用了 foo 函数,所以 foo 函数体内的 this
指向的就是 window
对象。
globle
对象了。 匿名函数中的 this 也是指向全局对象的。
再看个例子:
var name = 'window'var a = { name: 'a', foo: function() { console.log(this.name) }}a.foo() // 'a'var foo2 = a.foofoo2() // 'window'复制代码
改变 this 的指向
new
实例化对象。
new 运算符做了:申请内存用于储存对象,将 this 指向该对象,执行构造函数代码,返回对象给变量。
function User(name) { this.name = name}var a = new User('小a')复制代码
_this = this
var name = 'window'var a = { name: 'a', foo: function() { setTimeout(function() { console.log(this.name) }, 0) }, foo2: function() { var _this = this setTimeout(function(){ console.log(_this.name) }, 0) }}a.foo() // 'window'a.foo2() // 'a'复制代码
apply、call、bind
apply 与 call 差不多,主要是传参不同,都是将 this 改变并执行函数,而 bind 是将函数返回但没执行。
var name = 'window'var a = { name: 'a', foo: function(x, y) { console.log(this.name + x + y) }}a.foo.call(this, 1, 2) // 'window12'a.foo.apply(this, [1, 2]) // 'window12'var foo2 = a.foo.bind(this, 1, 2)foo2() // 'window12'复制代码
箭头函数
箭头函数不绑定 this,没有自己的 this ,必须通过作用域链决定其值。也就是箭头函数中的 this 就是父级作用域中的 this
var name = 'window'var a = { name: 'a', foo: () => { console.log(this.name) }, foo2: function() { setTimeout(()=>{ console.log(this.name) }, 0) }}a.foo() // 'window'a.foo2() // 'a'复制代码
参考资料: