站点工具

用户工具


手写bind、call、apply

bind、call、apply都是用来指定一个函数内部的this的值, 先看看bind、call、apply的用法

var year = 2021
function getDate(month, day) {
	return this.year + '-' + month + '-' + day
}
 
let obj = {year: 2022}
getDate.call(null, 3, 8)    //2021-3-8
getDate.call(obj, 3, 8)     //2022-3-8
getDate.apply(obj, [6, 8])  //2022-6-8
getDate.bind(obj)(3, 8)     //2022-3-8

实现call

Function.prototype.call2 = function(context, ...args) {
  context = (context === undefined || context === null) ? window : context
	context.__fn = this
  let result = context.__fn(...args)
  delete context.__fn
  return result
}

实现apply

Function.prototype.apply2 = function(context, args) {
  context = (context === undefined || context === null) ? window : context
	context.__fn = this
  let result = context.__fn(...args)
  delete context.__fn
  return result
}

实现bind

Function.prototype.bind2 = function(context, ...args1) {
  context = (context === undefined || context === null) ? window : context
	let _this = this
  return function(...args2) {
  	context.__fn = _this
    let result = context.__fn(...[...args1, ...args2])
    delete context.__fn
    return result
  }
}

问题:如果绑定的对象不允许新增属性怎么办?

饥人谷一直致力于培养有灵魂的编程者,打造专业有爱的国内前端技术圈子。如造梦师一般帮助近千名不甘寂寞的追梦人把编程梦变为现实,他们以饥人谷为起点,足迹遍布包括facebook、阿里巴巴、百度、网易、京东、今日头条、大众美团、饿了么、ofo在内的国内外大小企业。 了解培训课程:加微信 xiedaimala03,官网:https://jirengu.com

若愚 · 2023/02/09 10:34 · 手写bind_call_apply_手写系列八.txt