我正在尝试使用 push() 方法将一个元素添加到数组中,但显然,我无法从我的函数范围访问该数组。
以下是我的架构摘要:
class Test{
myArray;
aMethod() {
Divs.forEach(
...
let myElement = ...;
div.addEventListener("click",
function(){
if(...){
this.myArray.push(myElement);
我确信问题来自数组。 执行代码时,我有一个错误告诉我推送不是“未定义”的属性。另外,在 Visual Code Studio 中,当我单击函数中的“myArray”一次时,我发现它与我在顶部声明的不一样。
我曾尝试在不同的地方声明它,但从未成功。我也尝试像 myArray = []
那样声明它。
最奇怪的是 myElement
可以从这个函数的作用域访问,所以我试图在完全相同的地方声明我的数组:let myArray
。 ..它没有用。
有人看到可疑的东西吗?
感谢您抽出宝贵时间。
答案 0 :(得分:0)
您需要了解 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
上重新创建绑定