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
对象。
当然如果是在 Node.js 环境下,上述 this 指向的就是 globle
对象了。
匿名函数中的 this 也是指向全局对象的。
再看个例子:
var name = 'window'
var a = {
name: 'a',
foo: function() {
console.log(this.name)
}
}
a.foo() // 'a'
var foo2 = a.foo
foo2() // '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'
参考资料:
juejin.cn/post/684490…