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));

posted @   Clematis  阅读(27)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示