首页 \ 问答 \ 如何在ES6箭头函数调用的函数中使用`this`?(How to use `this` in a function called by an ES6 arrow function? [duplicate])

如何在ES6箭头函数调用的函数中使用`this`?(How to use `this` in a function called by an ES6 arrow function? [duplicate])

这个问题在这里已有答案:

我理解(我认为)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函数: httpsthis.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 in handleAuthResult? I do not want to use the old function () {}.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 on this.handleAuthResult in ES6: https://jsfiddle.net/m9e7j4ds/


原文:https://stackoverflow.com/questions/35825833
更新时间:2023-07-02 21:07

最满意答案

您可以使用余数运算符( % )将哈希代码映射到数组的索引:

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 use obj.getHashCode ("SomeString") & (yourArray.length - 1).

相关问答

更多
  • 我加两分钱: 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 ...
  • 但它似乎在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等等),在您的情况下,将 ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)