自己动手实现call、 apply、 bind 方法

实现call方法:

function person(a, b, c, d) {
  console.log(this.name)
  console.log(a, b, c, d)
}
let man = {
  name: 'zachary'
}

Function.prototype.newCall = function(obj) {
    obj = obj || window
    obj.p = this
    let newArguments = []
    for(let i = 1; i < arguments.length; i++) {
      newArguments.push( arguments[i] )
    }
    obj.p(...newArguments)
    delete obj.p
}
person.call(man, 1, 2, 3, 4)

运行结果如下
在这里插入图片描述
实现apply方法:(跟call区别是使用数组接受所有参数)

function person(a, b, c, d) {
  console.log(this.name)
  console.log(a, b, c, d)
}
let man = {
  name: 'zachary'
}

Function.prototype.newApply = function(obj, arr) {
    obj.p = this
    if(!arr) obj.p()
    else {
    	let newArguments = []
    	for(let i = 0; i < arr.length; i ++) {
				newArguments.push(  arr[i] )
		 }
		 obj.p(...newArguments )
	}
    delete obj.p
}
person.call(man, 1, 2, 3, 4)

结果:在这里插入图片描述
实现bind方法:

function person(a,b,c,d) {
  console.log(this.name)
  console.log(a,b,c,d)
}
let man = {name: 'zachary'}

Function.prototype.newBind = function( obj ) {
  let that = this
  let arr1 = Array.prototype.slice.call(arguments, 1)
  return function() {
      let arr2 = Array.prototype.slice.call(arguments)
      console.log(arr1.concat(arr2))
console.log(arr1)
console.log(arr2)
      that.apply(obj, arr1.concat(arr2))
  }
}
person.newBind(man, 1,2,3)(5)

结果:
自己动手实现call、 apply、 bind 方法_第1张图片

你可能感兴趣的:(javascript)