call、apply、bind
这三个函数都是Function原型上的方法,它们的作用就是改变函数执行时this的指向。
call、apply、bind的区别:
- call和apply在改变this指向的同时执行了函数,而bind改变了this指向然后将函数返回
- 使用call时向函数传递参数是一个一个的传入,而使用apply时向函数传递参数是将参数放入数组中传入
function fun (y, z) {
console.log(this.x + y + z)
}
var obj = {
x: 1
}
fun.apply(obj, [2, 3]) // 6
fun.call(obj, 2, 3) // 6
fun.bind(obj)(2, 3) // 6
实现call:
Function.prototype.myCall = function (context) {
if (context == null) {
context = window
} else {
context = Object(context)
}
let args = [...arguments].slice(1)
const fn = Symbol('fn')
context[fn] = this
const result = context[fn](...args)
delete context[fn]
return result
}
function fun (y, z) {
console.log(this.x + y + z)
}
var obj = {
x: 1
}
fun.myCall(obj, 2, 3) // 6
实现apply:
Function.prototype.myApply = function (context) {
if (context == null) {
context = window
} else {
context = Object(context)
}
const fn = Symbol('fn')
context[fn] = this
let result
if (arguments[1]) {
result = context[fn](...arguments[1])
} else {
result = context[fn]()
}
delete context[fn]
return result
}
function fun (y, z) {
console.log(this.x + y + z)
}
var obj = {
x: 1
}
fun.myApply(obj, [2, 3]) // 6
实现bind:
Function.prototype.myBind = function (context) {
var _this = this
var args = [...arguments].slice(1)
return function F () {
if (this instanceof F) {
return new _this(...args, ...arguments)
}
return _this.apply(context, args.concat(...arguments))
}
}
function fun (y, z) {
console.log(this.x + y + z)
}
var obj = {
x: 1
}
fun.myBind(obj)(2, 3) // 6