JavaScript的this
指向
Js,函數的調用方式決定this
的值
function f1(){
console.log(this)
}
f1() // window
bind
,apply
,call
可以更改this
的指向
call()
call()
第一個參數是指向的對象,當爲null
或undefined
時指向window
;第二個是傳遞的參數(任意類型)
function f1(){
console.log(this)
}
var obj = {}
f1.call(obj) // obj
f1()//window
apply()
apply()
和call()
類似,但第二個參數需要爲按順序的數組。
function f1(){
console.log(this)
}
var obj = {}
f1.apply(obj,[])//obj
f1()//window
bind()
bind()
參數與call()
相同,但不會立刻執行,而是返回綁定新this
的對象。
function f1(){
console.log(this)
}
var obj = {}
var i = f1.bind(obj)
i()//obj
手寫call()
Function.prototype.myCall(content){
content = content || window
content.fn = this
var arg = [...content].slice(1)
let result = content.fn(...arg)
delete content.fn
return result
}
手寫apply()
Function.prototype.myApply(content){
content = content || window
content.fn = this
let result
if(arguments[1]){
result = content.fn(...arguments[1])
}else{
result = content.fn()
}
delete content.fn
retuern result
}
手寫bind()
Function.prototype.myBind(content){
let that = this
//支持柯里化
let arg = [...arguments].slice(1)
return function(){
//支持柯里化
let args = [...arg]
return that.apply(content,arg.conact(args))
}