JavaScript修改this指向bind、call、apply
修改this指向涉及到的方法:
bind、call、apply
bind说明:调用之后不会直接请求目标函数,而是会返回一个修改了this指向的函数,用于后面调用
function fun(old, gender) { console.log(this.name, old, gender)//"张三",12,"男" } let obj = { name: '张三' } let newfun = fun.bind(obj, 12) newfun("男")
call说明:函数体调用call函数会直接请求目标函数,call里面用逗号方式传参
function fun1(old, gender) { console.log(this.name, old, gender)//"张三",30,"女" } let obj = { name: '张三' } let newfun = fun1.call(obj,30,'女')
apply说明:函数体调用apply函数会直接请求目标函数,call里面用数组方式传参
function fun1(old, gender) { console.log(this.name, old, gender)// "张三",30,"女" } let obj = { name: '张三' } let newfun = fun1.apply(obj, [30, '女'])