简体   繁体   English

我如何在 javascript 中使用它

[英]How do i use this in javascript

hello i am trying to access the length of an arrary i made inside a function how do i use the "this" to access it.你好,我正在尝试访问我在 function 中制作的数组的长度,我如何使用“this”来访问它。 Here is my code这是我的代码

let hashtable = new Arrary(50)
// create a hashfunction 
let gethash = (key)=>{
    // make sure all value passed in are strings 
        let keyStr = key.toString();
        let sum = 0
        for (let i = 0; i < keyStr.length; i++) {
            sum =+ keyStr.charAt(i)
        }
        return sum % this.hashtable.length

}

I am learning hashmaps in data structure and algorithm, i want to use the the length of the hash table to ensure that my hashfunction falls between the size of the arrary我正在学习数据结构和算法中的哈希图,我想使用 hash 表的长度来确保我的哈希函数在数组大小之间

Does it not work without the this keyword?没有this关键字就不能工作吗?

let hashtable = new Arrary(50)
// create a hashfunction 
let gethash = (key)=>{
    // make sure all value passed in are strings 
        let keyStr = key.toString();
        let sum = 0
        for (let i = 0; i < keyStr.length; i++) {
            sum =+ keyStr.charAt(i)
        }
        return sum % hashtable.length

}

You aren't accessing something bound to a class or object, so you should be able to treat it like a normal variable.您没有访问绑定到 class 或 object 的内容,因此您应该能够将其视为普通变量。


More about the this keyword:有关this关键字的更多信息:

In most cases, the value of this is determined by how a function is called (runtime binding).在大多数情况下, this 的值取决于 function 的调用方式(运行时绑定)。 It can't be set by assignment during execution, and it may be different each time the function is called.执行时不能赋值设置,每次调用function时可能不同。 ES5 introduced the bind() method to set the value of a function's this regardless of how it's called, and ES2015 introduced arrow functions which don't provide their own this binding (it retains the this value of the enclosing lexical context). ES5 引入了 bind() 方法来设置函数的 this 的值,而不管它是如何被调用的,ES2015 引入了不提供自己的 this 绑定的箭头函数(它保留了封闭词法上下文的 this 值)。

Source 资源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM