js修改函數內部的this指向
在調用函數的時候偶爾在函數內部會使用到this,在使用this的時候發現並不是我們想要指向的對象.可以通過bind,call,apply來修改函數內部的this指向.
默認在瀏覽器下script標簽內定義的函數,調用的時候函數內部的this指向window(瀏覽器窗口對象)
<script>
var a=2
function hello(){
console.log(this)
console.log(this.a)
}
hello()
//輸出: window => object
//輸出: 2
</script>
使用bind來修改內部的this指向 bind(option) 函數內部的this指向option這個對象
<script>
var a=2
var obj={
a:"a"
}
function hello(){
console.log(this)
console.log(this.a)
}
hello=hello.bind(obj)
hello()
//輸出: obj => { a:'a' }
//輸出: 'a'
</script>
使用call來修改內部的this指向 call(option) 函數內部的this指向option這個對象
var a=2
var obj={
a:"a"
}
function hello(){
console.log(this)
console.log(this.a)
}
hello.call(obj)
//輸出: obj => { a:'a' }
//輸出: 'a'
使用apply來修改內部的this指向 apply(option) 函數內部的this指向option這個對象
var a=2
var obj={
a:"a"
}
function hello(){
console.log(this)
console.log(this.a)
}
hello.apply(obj)
//輸出: obj => { a:'a' }
//輸出: 'a'
bind ,call ,apply 的區別
- bind是只改變函數內部this指向,但不自調用
- call,apply 改變函數內部指向並且自調用
- call第一個參數是需要指向的對象,之后的參數是函數內部的形參可以訪問
- apply第一個參數是需要指向的對象,第二個參數是數組格式,函數內部的形參可以訪問
//call
var a = 2
var obj={
a:'a'
}
function hello(a, b, c) {
console.log(this)
console.log(a, b, c)
}
hello.call(obj,1,2,3) // { a:'a' } 1,2,3
//apply
var a = 2
var obj={
a:'a'
}
function hello(a, b, c) {
console.log(this)
console.log(a, b, c)
}
hello.apply(obj,[1,2],3,4) // { a:'a' } 1,2,undefind,undefind
