在JavaScript中,
call
、apply
和bind
是Function
对象自带的三个方法,这三个方法的主要作用是改变函数中的this
指向。
call
、apply
、bind
方法的共同点和区别:apply
、call
、bind
三者都是用来改变函数的this对象的指向的;apply
、call
、bind
三者第一个参数都是this要指向的对象,也就是想指定的上下文(函数的每次调用都会拥有一个特殊值——本次调用的上下文(context)——这就是this
关键字的值。);apply
、call
、bind
三者都可以利用后续参数传参;bind
是返回对应函数,便于稍后调用,bind也是一个‘’柯里化函数‘’;
apply
、call
则是立即调用 。
实现call函数
Function.prototype.myCall = function (content) {
content = content || window
content.fn = this
let args = Array.from(arguments).slice(1)
let result = content.fn(...args)
delete content.fn
return result
}
function fun(args) {
console.log("this.personSName ==>",this.personSName) //小明星
console.log("this.age ==>",this.age) //20
console.log("this.gender ==>",this.gender) //女
console.log("args ==>",args) //'参数'
}
let obj = {
personSName: '小明星',
age: 20,
gender: '女'
}
fun.myCall(obj,'参数')
打印结果
实现apply函数
Function.prototype.myApply = function (content) {
content = content || window;
content.fn = this;
//arguments 函数所传的参数数组 (伪数组)
//Array.from 将伪数组转成真正的数组 也可使用ES6的语法 [...arguments]
let args = Array.from(arguments)
let result;
if (args[1] instanceof Array && args[1].length > 0) {
result = content.fn(...args[1])
} else {
result = content.fn()
}
delete content.fn;
return result;
}
function fun(args) {
// console.log("this.name ==>",this.name)
console.log("this.personSName ==>",this.personSName)
console.log("this.age ==>",this.age)
console.log("this.gender ==>",this.gender)
console.log("args ==>",args)
console.log("arguments ==>",[...arguments])
}
let obj = {
personSName: '小明星',
age: 20,
gender: '女'
}
fun.myApply(obj,['123',456])
打印结果
实现bind函数
Function.prototype.myBind = function (content){
content = content || window
let args = [...arguments].slice(1);
let _this = this
return function F () {
return _this.call(content,...args,...arguments)
}
}
function fun() {
// console.log("this.name ==>",this.name)
console.log("this.personSName ==>",this.personSName)
console.log("this.age ==>",this.age)
console.log("this.gender ==>",this.gender)
console.log("arguments ==>",...arguments)
}
let obj = {
personSName: '小明星',
age: 20,
gender: '女'
}
let funcBind = fun.myBind(obj,'muBind的参数')//返回的是一个函数,需要调用函数才会执行
funcBind() //调用方法时也可传参数
打印结果
文章到此结束,请大家多多指教