You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Function.prototype.mybind=function(){varslice=Array.prototype.slicevarthatFunc=this,thatArg=arguments[0]varargs=slice.call(arguments,1)if(typeofthatFunc!=='function'){// closest thing possible to the ECMAScript 5// internal IsCallable functionthrownewTypeError('Function.prototype.bind - '+'what is trying to be bound is not callable')}returnfunction(){varfuncArgs=args.concat(slice.call(arguments))returnthatFunc.apply(thatArg,funcArgs)}}Function.prototype.mycall=function(context, ...args){if(!context){console.log('不存在')context=global}if(typeofcontext!=='object'){console.log('不是对象')context=global}letsay=Symbol()// 防止覆盖掉原有属性context[say]=this// 这里的this为需要执行的方法constres=context[say](...args)deletecontext[say]returnres}
奇怪的Function.prototype.call.bind()
Function.prototype.call.bind() 今天第一次在掘金上看到了这样的使用方法。
这样的用法看的我一脸蒙蔽。
这里我们找2个垫片,方便我们调试。
Function.prototype.call()
先看一个简单的:
Function.prototype是函数的原型对象,所有函数都要继承它,相当于执行了一个空函数。
Function.prototype.mycall.mycall()
接下来是升级版:
Function.prototype.mycall.mybind()
终极版:
这与其他函数不同,bind会返回一个绑定好this的闭包函数。
参考
原型
手写实现call,apply,bind
一句有趣的JS代码
js Function.prototype.call.bind(Array.prototype.slice),为啥要这么写?
在JavaScript中借用方法
JS魔法堂:再次认识Function.prototype.call
关于Function.prototype.call.bind()的疑惑?
The text was updated successfully, but these errors were encountered: