js函数执行的时都有执行期上下文,也就是我们所说的this,当函数空执行的时候,在非严格模式下this指向全局gloal或者window对象,在严格模式下指向undefined。一般我们可以通过apply或者call来改变this的指向,除此之外还可以通过bind来绑定this的指向。
Function.prototype.myBind = function() {
let context = [].shift.apply(arguments)
let outArgs = [].slice.call(arguments)
let self = this
return function() {
let inArgs = [].slice.call(arguments)
self.call(context,[].concat.call(outArgs,inArgs))
}
}
var test = function() {
console.log(this)
}.myBind({a:12})
test() // {a:12}

JS函数执行时有执行期上下文this,非严格模式下空执行函数this指向全局或window对象,严格模式下指向undefined。可通过apply、call改变this指向,也能使用bind绑定this指向。
2043

被折叠的 条评论
为什么被折叠?



