hgq's docs
主页
ES6-阮一峰 (opens new window)
Vue文档 (opens new window)
Axios文档 (opens new window)
Vue Router (opens new window)
Vuex文档 (opens new window)
面试题-Vue (opens new window)
面试题-JS (opens new window)

guoguoqiqi

漫不经心的向往
主页
ES6-阮一峰 (opens new window)
Vue文档 (opens new window)
Axios文档 (opens new window)
Vue Router (opens new window)
Vuex文档 (opens new window)
面试题-Vue (opens new window)
面试题-JS (opens new window)
  • call的实现
  • apply的实现
  • bind的实现
  • new的实现
  • instanceof的实现
  • Object create()的实现
  • Object assign()的实现
  • Promise的实现
  • 实现防抖函数(debounce)
  • 实现节流函数(throttle)
  • 深拷贝(deepclone)
  • 数组扁平化的实现(flat)
  • 函数柯里化
  • EventEmitter 实现
  • 数组的随机排序
  • 通用的事件侦听器函数
  • 实现一个JSONP
  • 数组的map方法
  • 数组的forEach方法
  • 数组的find方法
  • 数组的findIndex方法
  • 数组的some方法
  • 数组的filter方法
  • 数组的every方法
  • 数组的includes方法
  • 数组的fill方法
  • 数组的join方法
  • 数组的flat方法
  • 用setTimeout实现setInterval
  • 用setInterval实现setTimeout
  • 实现一个较完善的深拷贝
  • 代码手写
guoguoqiqi
2022-02-13

call的实现

  • 第一个参数为null或者undefined时,this指向全局对象window,值为原始值的指向该原始值的自动包装对象,如 String、Number、Boolean
  • 为了避免函数名与上下文(context)的属性发生冲突,使用Symbol类型作为唯一值
  • 将函数作为传入的上下文(context)属性执行
  • 函数执行完成后删除该属性
  • 返回执行结果
Function.prototype.myCall = function (ctx, ...args) {
	// 简单处理未传ctx上下文,或者传的是null和undefined等场景
	if (!ctx) {
		ctx = typeof window !== "undefined" ? window : global;
	}
	// 暴力处理 ctx有可能传非对象
	ctx = Object(ctx);
	// 用Symbol生成唯一的key
	const fnName = Symbol();
	// 这里的this,即要调用的函数
	ctx[fnName] = this;
	// 将args展开,并且调用fnName函数,此时fnName函数内部的this也就是ctx了
	const result = ctx[fnName](...args);
	// 用完之后,将fnName从上下文ctx中删除
	delete ctx[fnName];

	return result;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

apply的实现→

最近更新
01
vuex数据持久化怎么做
05-22
02
vue的动态路由怎么配置使用
05-22
03
vue权限控制一般怎么做
05-22
更多文章>
Theme by Vdoing | Copyright © 2022-2022 Guoquoqiqi | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式