this 的指向,apply、bind、call 一块儿搞定~javascript
this 是在执行函数时,建立的上下文对象中的一个属性,它容许在调用函数时决定哪一个对象是焦点。因此 this
通常是在函数执行时肯定的。java
通常状况下,请记住 "谁调用我,我就表明谁"。
谁调用这个函数,函数中的 this 就指向谁。app
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 也是指向全局对象的。post
再看个例子:ui
var name = 'window'
var a = {
name: 'a',
foo: function() {
console.log(this.name)
}
}
a.foo() // 'a'
var foo2 = a.foo
foo2() // 'window'
复制代码
new
实例化对象。new 运算符作了:申请内存用于储存对象,将 this 指向该对象,执行构造函数代码,返回对象给变量。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 差很少,主要是传参不一样,都是将 this 改变并执行函数,而 bind 是将函数返回但没执行。spa
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 就是父级做用域中的 thiscode
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.im/post/59bfe8…