欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

手写bind call apply函数

程序员文章站 2022-03-08 09:43:33
...

apply

Function.prototype.myApply = function (thisArg, ArgArray) {
    if (typeof thisArg == 'undefined' || typeof thisArg == null) {
      thisArg = window
    }

    let fnSymbol = Symbol()
    thisArg[fnSymbol] = this
    let ret = thisArg[fnSymbol](...ArgArray)
    delete thisArg[fnSymbol]
    return ret
  }

  function say(age) {
    console.log(`我的名字是${this.name},年龄${age}啦`)
  }
  say.myApply({ name: 'zhq' }, [18])

call

Function.prototype.myCall = function (thisArg, ...ArgArray) {
    if (typeof thisArg === 'undefined' || typeof thisArg === null) {
      thisArg = window
    }

    let fnSymbol = Symbol()
    thisArg[fnSymbol] = this
    let ret = thisArg[fnSymbol](...ArgArray)
    delete thisArg[fnSymbol]
    return ret
  }

  function say(age) {
    console.log(`我的名字是${this.name},年龄${age}啦`)
  }
  say.myApply({ name: 'zhq' }, [18])

bind

Function.prototype.myBind = function (thisArg, ...ArgArray) {
    let thatFunc = this
    return function () {
      thatFunc.apply(thisArg, ArgArray)
    }
  }

上面仅为实现,没有兼容性
Polyfill写法

if (!Function.prototype.bind){
	;(function(){
		let slice = Array.prototype.slice;
		let thatArg = arguments[0];
    	let args = slice.call(arguments, 1);
		Function.prototype.bind = function (thisArg, ...ArgArray) {
		    let thatFunc = this
		    return function () {
		    	let funcArgs = args.concat(slice.call(arguments))
	      		thatFunc.apply(thatArg, funcArgs)
	   	 	}
  		}
	})()
}
相关标签: js