一 写前需要先了解一下他们的用法
call 和 apply 是为了动态改变 this 而出现的.传入call的参数只能是单个参数,不能是数组。apply可传入数组。
区别
func.call(this, arg1, arg2); func.apply(this, [arg1, arg2])
call
Function.prototype.call1 = function (context) { var context = context || window; context.fn = this let args = [...arguments].slice(1) let result = context.fn(...args) delete context.fn return result }
apply
Function.prototype.apply1 = function (context) { var context = context || window; context.fn = this; let args = arguments[1] let result; if (args) { result = context.fn(...args) } else { result = context.fn() } delete context.fn return result }
bind
暂无
测试
var name = '呵呵' var foo = { name: '嘿嘿', } function bar(a, b, c) { return { name: this.name, a, b, c } } console.log(bar.call1(foo, 11, 12, 13)) console.log(bar.apply1(foo, [11, 12, 13])) console.log(bar.bind1(foo, 11))