我根本不明白为什么它会给出这个错误。
这是我在 chrome 控制台上测试的结果:
> var mySet;
<- undefined
> mySet = new Set;
<- Set {}
> mySet.add('foo', 'bar', 'baz') // Worked as expected
<- Set {"foo"} // just the first argument was added
> ['bar', 'baz'].forEach(mySet.add)
X-> VM1529:1 Uncaught TypeError:
Method Set.prototype.add called on incompatible receiver undefined(…)
提前致谢。
在这种情况下add
方法失去其内在this
当您将其作为回调传递时的上下文,因此您需要使用bind
:
['bar', 'baz'].forEach(mySet.add.bind(mySet));
or
['bar', 'baz'].forEach((item) => mySet.add(item));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)