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…