JavaScript:函数绑定(对象)的问题 - "this"保持全局对象



我在Javascript中绑定函数时遇到问题。

请确保我阅读了StackOverflow的所有答案(像这个(,并遵循的说明和示例Mozilla的开发人员指导

这是我的代码的相关部分:

class Collection extends Array {
constructor (...args) {
super(...args)
}
each (callback) {
this.forEach(element => {
callback.bind(element)(element) 
// bind the function THEN call it with element as argument
// but I also tried :
// callback.bind(element)()
// callback.call(element, element)
// let bound = callback.bind(element); bound()
})
}
}
//the tests :
let el1 = {x:1, y:"somevars"}
let el2 = {x:42, y:"another"}
let col = new Collection()
col.push(el1)
col.push(el2)
// the test
col.each(element => console.log(Object.keys(this)))
// and I get ['console', 'global', 'process' ...]   all the global variables 
// instead of ['x','y'] which is what I want

我真的不明白为什么它不起作用。。。

对于上下文,它是为了解决一个有趣的问题Codewars上的kata,不是生死攸关的问题。

好的,正如@Teemu所指出的,箭头函数不能绑定。。。

但有了这种洞察力,我可以找到绕过这一点的方法另一篇StackOverflow的帖子这给了一个诀窍:

(粘贴自帖子的副本(

function arrowBind(context, fn) {
let arrowFn;
(function() {
arrowFn = eval(fn.toString());
arrowFn();
}).call(context);
}
arrowBind(obj, () => {console.log(this)});

这很好,新的这是上下文。。。

但这并不能解决我的问题("拥有没有定义"(我需要进一步研究

最新更新