如何在ES6箭头函数调用的函数中使用`this`?(How to use `this` in a function called by an ES6 arrow function? [duplicate])
这个问题在这里已有答案:
- 如何在回调中访问正确的`this`? 8个答案
我理解(我认为)ES6中的箭头函数使用Lexical ,但我不确定为什么胖箭头函数调用的函数会
this
设置为未定义。我需要做什么才能在
handleAuthResult
调用handleAuthResult
? 如果我不需要,我不想使用旧function () {}.bind(this)
。"use strict"; class Example { constructor() { this.checkAuth(); } checkAuth() { document.write("Checking auth now. "); var iid = setInterval(() = > { if (true) { // Have to do some dumb check here clearInterval(iid); this.authenticate(this.handleAuthResult) } }, 500); } authenticate(callback) { callback({ value: true }); } handleAuthResult(result) { document.write(`The result is ${result.value}.`); this.setResult(result, this.loadThePage) // ^ `this` is undefined here. How can I ever set the result? } // Another asynchronous thing setResult(result, callback) { callback(); } loadThePage() { document.write("The code never gets here, but the page should load now. "); } }; var example = new Example();
谢谢! https://jsfiddle.net/vujev4dj/
编辑:在我对此标记为重复的辩护中,我期望的行为在下面的小提琴中起作用,这就是为什么我期望
this.handleAuthResult
在ES6中的this.handleAuthResult
上使用bind
函数: https :this.handleAuthResult
/ m9e7j4ds /This question already has an answer here:
I understand (I think) that arrow functions in ES6 use Lexical this, but I'm not sure why a function called by a fat arrow function would have
this
set as undefined.What do I have to do to be able to call
this.setResult
inhandleAuthResult
? I do not want to use the oldfunction () {}.bind(this)
if I don't need to."use strict"; class Example { constructor() { this.checkAuth(); } checkAuth() { document.write("Checking auth now. "); var iid = setInterval(() = > { if (true) { // Have to do some dumb check here clearInterval(iid); this.authenticate(this.handleAuthResult) } }, 500); } authenticate(callback) { callback({ value: true }); } handleAuthResult(result) { document.write(`The result is ${result.value}.`); this.setResult(result, this.loadThePage) // ^ `this` is undefined here. How can I ever set the result? } // Another asynchronous thing setResult(result, callback) { callback(); } loadThePage() { document.write("The code never gets here, but the page should load now. "); } }; var example = new Example();
Thanks! https://jsfiddle.net/vujev4dj/
Edit: in my defense of this being marked as duplicate, the behaviour I expected does work in the following fiddle, which is why I expected to not have to use the
bind
function onthis.handleAuthResult
in ES6: https://jsfiddle.net/m9e7j4ds/
原文:https://stackoverflow.com/questions/35825833
最满意答案
您可以使用余数运算符(
%
)将哈希代码映射到数组的索引:int index = obj.getHashCode ("SomeString") % yourArray.length;
当然,您应该能够处理冲突(即两个或多个Strings映射到同一个数组索引的情况)。
HashMap
通过在数组的每个索引中存储一个条目实例来处理这种潜在的冲突,该条目实例可以指向映射到同一索引的下一个条目(从而形成链接列表)。编辑:
正如下面正确评论的那样,
%
运算符不适用于负哈希码。 作为替代方案,您可以使用Math.floorMod (在Java 8中引入):int index = Math.floorMod (obj.getHashCode ("SomeString"), yourArray.length);
无论哈希码的符号如何,都可以保证返回非负索引。
或者您可以采用
HashMap
实现中使用的替代方法。 如果数组的长度始终为2的幂,则可以使用obj.getHashCode ("SomeString") & (yourArray.length - 1)
。You could use the remainder operator (
%
) to map your hash code to an index of an array :int index = obj.getHashCode ("SomeString") % yourArray.length;
Of course, you should be able to handle clashes (i.e. situations in which two or more Strings are mapped to the same array index).
HashMap
handles such potential clashes by storing in each index of the array an entry instance that can point to the next entry that was mapped to that same index (thus forming a linked list).EDIT:
As was correctly commented below, the
%
operator wouldn't work for negative hash codes. As an alternative, you can use Math.floorMod (introduced in Java 8) instead :int index = Math.floorMod (obj.getHashCode ("SomeString"), yourArray.length);
This is guaranteed to return a non-negative index, regardless of the sign of the hash code.
Or you can take the alternative used in
HashMap
implementation. If the length of your array is always a power of 2, you can useobj.getHashCode ("SomeString") & (yourArray.length - 1)
.
相关问答
更多-
从数组中创建一个哈希值,其中值是元素的索引(Create a hash out of an array where the values are the indices of the elements)[2021-07-14]
我加两分钱: array = [1,3,4,5,6,6,6,8,8,8,9,7,7,7] hash = {} array.map.with_index {|val, idx| [val, idx]}.group_by(&:first).map do |k, v| hash[k] = v[0][1] if v.size == 1 hash[k] = v.map(&:last) if v.size > 1 end p hash #=> {1=>0, 3=>1, 4=>2, 5=>3, 6=>[4, ... -
您可以使用余数运算符( % )将哈希代码映射到数组的索引: int index = obj.getHashCode ("SomeString") % yourArray.length; 当然,您应该能够处理冲突(即两个或多个Strings映射到同一个数组索引的情况)。 HashMap通过在数组的每个索引中存储一个条目实例来处理这种潜在的冲突,该条目实例可以指向映射到同一索引的下一个条目(从而形成链接列表)。 编辑: 正如下面正确评论的那样, %运算符不适用于负哈希码。 作为替代方案,您可以使用Math.f ...
-
这是我的工作: (1..a.size).zip(a) # => [[1, "a"], [2, "b"], [3, "c"], [4, "d"]] (1..a.size).zip(a).to_h # => {1=>"a", 2=>"b", 3=>"c", 4=>"d"} Here is my work : (1..a.size).zip(a) # => [[1, "a"], [2, "b"], [3, "c"], [4, "d"]] (1..a.size).zip(a).to_h # => {1=>"a", ...
-
你的代码有两个问题。 首先是当h为空并且你写出h[2] << 1 ,由于h没有键2 , h[2]返回默认值,所以这个表达式变成[] << 1 #=> [1] ,但[1]未附加到散列,因此不会添加任何键和值。 你需要写h[2] = h[2] << 1 1 。 如果你这样做,你的代码返回h #=> {3=>[0, 1, 2, 3], 2=>[0, 1, 2, 3], 4=>[0, 1, 2, 3]} 。 不幸的是,这仍然是不正确的,这将我们带到了代码的第二个问题:您没有正确定义新创建的哈希默认值。 首先注意到 ...
-
这更可能 (lowerIndex + higherIndex)/ 2 溢出而不是 lowerIndex +(higherIndex-lowerIndex)/ 2。 例如,对于lowerIndex == higherIndex == Integer.MAX_VALUE / 2 + 1 。 编辑: 表达式等价的数学证明 l + (r - l)/2 (in java notation) = l + round_towards_zero((r - l) / ...
-
尝试这个: @kate = [] @kategoris.each do |kat| h = {} kat.attributes.each{|k,v| h[k] = v.respond_to?(:force_encoding) ? v.dup.force_encoding("UTF-8") : v } @kate << h end 要么 @kate = @kategoris.map{|k| k.attributes.inject({}){|h,(k,v)| h[k] = v.respond_t ...
-
您已经做了正确的事情来确定索引是否使用哈希。 答案是:事实并非如此。 MySQL 5.6的文档说他们还没有为InnoDB实现它 。 You've done the right thing for determining whether the index is using hash. The answer is: it isn't. The documentation for MySQL 5.6 says they haven't implemented it for InnoDB at all yet.
-
E1[E2]相当于*((E1)+(E2)) ,因此在第一种情况下(2+6-5)将首先计算。 因此没有问题。 引自N3337 5.2.1订阅 表达式E1 [E2]与*((E1)+(E2))相同(根据定义) E1[E2] is equivalent to *((E1)+(E2)), so in the first case (2+6-5) will be calculated first. Therefore there will be no problem. Quote from N3337 5.2.1 Su ...
-
是否有不同的方法来计算HashMap中的表索引(Are there different ways to calculate the table index in HashMap)[2022-01-16]
但它似乎在Java中的表现方式却截然不同。 实际上它们完全一样。 hash = hashfunc(key) // calculate hash value. 是相同的 hash = hash(key.hashCode()); 和 index = hash % array_size (assumes the hash is unsigned) 是相同的 return h & (length-1); 因为长度是2的幂。 But it seems the way it is performed ... -
要回答您的问题,“方法2”应该更快。 现在,这是一个非常加载的语句,它部分取决于哈希的本质(例如插入时的冲突 )。 但是,对于您的特定用例,我认为数组和哈希都是“工作的错误工具”。 通常,如果您使用哈希来检查唯一集合存在(提示提示),请使用set 。 最后一个想法,取决于你的例子是多么做作,可能有也可能没有价值。 如果你要存储一些有限的有序值(在你的例子中是'a' - 'd'),那么数组肯定是要走的路。 为什么? 因为您可以轻松地将字母表的值映射到数组索引(例如,映射到0,b映射到1等等),在您的情况下,将 ...