【发布时间】:2020-02-17 09:20:42
【问题描述】:
首先,我将当前传递的上下文复制到虚拟对象中。
然后我添加一个方法 fn 作为当前传递的函数。
虚拟对象存在于闭包中。
最后,我将返回一个函数,该函数使用最初传递的参数执行dummy.fn。
Function.prototype.bind2 = function(context, ...args){
var dummy = {...context}
dummy.fn = this
return function(){
return dummy.fn(...args)
}
}
编辑 1:在首次提出新虚拟对象的建议后,我将其更改为以下内容
Function.prototype.bind2 = function(context, ...args){
var dummy = Object.create(context)
dummy.fn = this
return function(){
return dummy.fn(...args)
}
}
编辑 2:对于扩展运算符修复,我使用了 eval:
Function.prototype.bind2 = function(){
var args = arguments;
var dummy = Object.create(args[0]);
dummy.fn = this;
return function(){
return eval('dummy.fn('+Object.values(args).slice(1,).join(',')+')')
}
}
【问题讨论】:
-
一个合适的 polyfill:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
标签: javascript polyfills