如何从函数范围访问数组
How to access an array from the scope of a function
我正在尝试使用 push() 方法将一个元素添加到数组中,但显然,我无法从我的函数范围访问该数组。
这是我的架构的总结:
class Test{
myArray;
aMethod() {
Divs.forEach(
...
let myElement = ...;
div.addEventListener("click",
function(){
if(...){
this.myArray.push(myElement);
我确定问题来自数组。
执行代码时,我有一个错误告诉我推送不是 'undefined' 的专有。另外,在 Visual Code Studio 上,当我单击一次函数中的“myArray”时,我发现它与我在顶部声明的不一样。
我曾尝试在多个地方声明它,但从未成功。我也试过这样声明 myArray = []
.
最奇怪的是myElement
可以从这个函数的范围内访问,所以我试着在完全相同的地方声明我的数组:let myArray
...没用。
有没有人看到可疑的东西?
感谢您的宝贵时间。
您需要了解 this
在 JavaScript 中的工作原理,我建议阅读 this & object prototypes 了解更多详情
这是一个解决方案:
class Test{
myArray;
aMethod() {
const myTestObj = this // store the Test instance in a variable myTestObj
Divs.forEach(
...
let myElement = ...;
div.addEventListener("click",
function(){
// In here `this` is bound to the global object
// because it will be invoked as a function, not a method, nor a constructor
if(...){
myTestObj.myArray.push(myElement); // Use myTestObj
另一个解决方案是:
class Test{
myArray;
aMethod() {
Divs.forEach(div => // Use an arrow function and only arrow functions in all the callbacks
// In here `this` is bound to the same object as in the upper scope
...
let myElement = ...;
div.addEventListener("click",
() => { // Arrow function here also
// In here `this` is bound to the same object as in the upper scope
if(...){
this.myArray.push(myElement); // Use this
因为 arrow functions 不在 this
上重新创建绑定
我正在尝试使用 push() 方法将一个元素添加到数组中,但显然,我无法从我的函数范围访问该数组。
这是我的架构的总结:
class Test{
myArray;
aMethod() {
Divs.forEach(
...
let myElement = ...;
div.addEventListener("click",
function(){
if(...){
this.myArray.push(myElement);
我确定问题来自数组。 执行代码时,我有一个错误告诉我推送不是 'undefined' 的专有。另外,在 Visual Code Studio 上,当我单击一次函数中的“myArray”时,我发现它与我在顶部声明的不一样。
我曾尝试在多个地方声明它,但从未成功。我也试过这样声明 myArray = []
.
最奇怪的是myElement
可以从这个函数的范围内访问,所以我试着在完全相同的地方声明我的数组:let myArray
...没用。
有没有人看到可疑的东西?
感谢您的宝贵时间。
您需要了解 this
在 JavaScript 中的工作原理,我建议阅读 this & object prototypes 了解更多详情
这是一个解决方案:
class Test{
myArray;
aMethod() {
const myTestObj = this // store the Test instance in a variable myTestObj
Divs.forEach(
...
let myElement = ...;
div.addEventListener("click",
function(){
// In here `this` is bound to the global object
// because it will be invoked as a function, not a method, nor a constructor
if(...){
myTestObj.myArray.push(myElement); // Use myTestObj
另一个解决方案是:
class Test{
myArray;
aMethod() {
Divs.forEach(div => // Use an arrow function and only arrow functions in all the callbacks
// In here `this` is bound to the same object as in the upper scope
...
let myElement = ...;
div.addEventListener("click",
() => { // Arrow function here also
// In here `this` is bound to the same object as in the upper scope
if(...){
this.myArray.push(myElement); // Use this
因为 arrow functions 不在 this