CALL&APPLY(JS)
call 与 apply
功能:改变this的指向
区别:函数的参数风格不一样。
call实现:
js构造函数继承
js数据类型
console.log(Object.prototype.toString.call({})==='[object 0bject]');
//true
console.log(0bject.prototype.toString.call([]));
//[object Array]
es5 伪数组转换为真数组
改变this指向
手写call
查看代码
var name ='hhh'
var person = {
getName: function(){
return this.name
// 这个this怎么指向person1
}
}
var person1 = {name: 'sss'}
//参数接受的改变this指向的参数
Function.prototype.myCall = function (context){
//这里面的this是谁??
//这里的this必须要是一个function,否则error
if (typeof this !== 'function') {
throw new Error( 'error ')
}
context = context || window
//考虑参数
//拿到除了第一个参数之外的参数
var args = [...arguments].slice(1)
console.log(args);
//return 1234
console.log(this);
//要在person1上面来假设有一个方法,此处命名fn
context.fn = this
var result = context.fn(...args)
delete context.fn
return result
}
console.log(person.getName.myCall(person1,1,2,3,4));
手写apply
查看代码
//apply手写
var name ='hhh'
var person = {
getName: function(){
return this.name
}
}
var person1 = {name: 'sss'}
//参数接受的改变this指向的参数
Function.prototype.myApply = function (context){
if (typeof this !== 'function') {
throw new Error( 'error ')
}
context = context || window
context.fn = this
let result
if(arguments[1]){
result = context.fn(arguments[1])
}
else{
result = context.fn()
}
delete context.fn
return result
}
console.log(person.getName.myApply(person1,1,2,3,4));
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端